我的SQL db中有2个表:
用户:id |电子邮件|宗教|政治
兴趣:id | user_id | interest_name
给定user1 id,找到至少有1个匹配兴趣的第二个用户的最佳方法是什么?另请注意,Users表中的宗教/政治也应该用于此匹配。
任何帮助表示赞赏, - 安迪
答案 0 :(得分: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 ))
答案 1 :(得分: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, 'user@userdomain.com', 'Muslim', 'Liberal'),
(2, 'user@differentdomain.com', 'Muslim', 'Conservative'),
(3, 'user@yadn.com', '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
为了匹配宗教信仰,你可以用“用户”这个表做同样的事情。
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