2011-02-06 30 views
0

同じような興味を持つ検索ユーザーID |電子メール|宗教|政治MySQLの:私は私のSQL DBに2つのテーブルを持っている

興味::id | user_id | interest_name

user1 idを指定すると、少なくとも1つの一致する興味を持つ第2のユーザーを見つける最良の方法は何ですか?また、このマッチには、Usersテーブルの宗教/政治も使用する必要があります。

すべてのヘルプは感謝、 - アンディ

+0

おそらくこれはあなたのコントロールの外にあるが、なぜ興味テーブルに宗教と政治を含みませんか?また、クエリはこのように少しシンプルになります。 – AJJ

+0

ちょっとAJweb - 私はまだそれを実際にやろうと考えています。 –

答えて

1
select * from users 
where id in (
select id from interests where interest_name in 
(select interest_name from interests where id = :current_user_id)) 
+0

ありがとうございます。シンプルだがトリッキー:)一致する興味があったものを返す簡単な方法はありますか? –

+0

2番目と3番目の選択では、_user_id_に対して参照を行う必要がありますが、_id_ではなく、Insterestsテーブル – pcofre

+0

@pcofreの行識別子だけであることに注意してください。ヘッドアップをありがとう。 –

1

(PostgreSQLの)

私は普通の利害の上に宗教と政治を高めるためにあなたの決定を主張しません。 (それはそれは良いアイデアだという意味ではありませんが、それはちょうど私がそれについてあなたと議論しないことを意味します。)

create table users (
user_id integer primary key, 
email_addr varchar(35) not null, 
current_religion varchar(35) not null default 'None', 
current_politics varchar(35) not null default 'None' 
); 

insert into users values 
(1, '[email protected]', 'Muslim', 'Liberal'), 
(2, '[email protected]', 'Muslim', 'Conservative'), 
(3, '[email protected]', 'Christian', 'Liberal'); 

create table interests (
user_id integer not null references users (user_id), 
user_interest varchar(20) not null, 
primary key (user_id, user_interest)); 

insert into interests values 
(1, 'Walks on the beach'), 
(1, 'Women'), 
(1, 'Polar bears'), 
(2, 'Walks on the beach'), 
(2, 'Women'), 
(2, 'Little Big Man'), 
(3, 'Running on the beach'), 
(3, 'Coffee'), 
(3, 'Polar bears'); 

-- Given one user id (1), find a different user with at least 
-- one matching interest. You can do this without referring 
-- to the users table at all. 

select t1.user_id, t1.user_interest, t2.user_id 
from interests t1 
inner join interests t2 on (t2.user_interest = t1.user_interest) 
where t1.user_id = 1 and t2.user_id <> 1; 

戻り

1 Walks on the beach 2 
1 Women    2 
1 Polar bears   3 

をも、宗教、たとえば、上のあなたを一致させるにはテーブル "users"で本質的に同じことをすることができます。

select t1.user_id, t1.current_religion as interest, t2.user_id 
from users t1 
inner join users t2 on (t1.current_religion = t2.current_religion) 
where t1.user_id = 1 and t2.user_id <> 1 

戻り

1 Muslim    2 

あなたが一緒にUNIONを使用して、宗教的利益と経常利益をもたらすために類似した構造を利用することができます。

select t1.user_id, t1.current_religion as interest, t2.user_id 
from users t1 
inner join users t2 on (t1.current_religion = t2.current_religion) 
where t1.user_id = 1 and t2.user_id <> 1 
union 
select t1.*, t2.user_id 
from interests t1 
inner join interests t2 on (t2.user_interest = t1.user_interest) 
where t1.user_id = 1 and t2.user_id <> 1; 

戻り

1 Walks on the beach 2 
1 Women    2 
1 Polar bears   3 
1 Muslim    2 
関連する問題