谁喜欢我了?

时间:2018-05-01 20:13:31

标签: mysql

我为其他用户提供了一个简单的表格。

我想吸引喜欢我的用户。

所以我试过了:

select c.user, h.id 
from heart h
left join heart hh 
    on hh.heart = h.user
left join users c 
    on h.heart = c.id // to get the user nick name
where h.user = '1' and hh.user = h.heart

心脏表:

  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user` INT(11) UNSIGNED NOT NULL, // who is liking
  `heart` INT(11) UNSIGNED NOT NULL, // who is liked

它适用于一方,显示两者都正确地喜欢它但不适合其他用户。任何想法为什么?或任何改善它的想法?

例如

  

用户1喜欢用户2

     

用户2喜欢用户1 =匹配=显示两者。

2 个答案:

答案 0 :(得分:1)

如果找到喜欢id为1的用户:

select c.user, c.id 
from heart h
inner join users c 
    on h.heart = c.id // to get the user nick name
where h.user = 1;

编辑:

SELECT h1.* FROM heart h1
INNER JOIN heart h2 ON h1.[user] = h2.heart AND exists (
      select * from heart h3
      where h1.[heart] = h2.[user]
    ); 

答案 1 :(得分:1)

我是#1用户。谁喜欢我(即我喜欢他们,他们喜欢我)?

在标准SQL中,这是一个简单的交叉查询:

select heart from heart where user = 1
intersect
select user from heart where heart = 1;
但是,MySQL并不支持INTERSECT。因此,将一个查询作为主查询,另一个查询子查询:

select heart
from heart 
where user = 1
and heart in (select user from heart where heart = 1);

select user
from heart 
where heart = 1
and user in (select heart from heart where user = 1);

一般情况下:谁喜欢回来(比如喜欢喜欢他们的人)?

select user
from heart h1
and exists
(
  select * 
  from heart h2
  where h2.user = h1.heart
    and h2.heart = h1.user
);

一般来说:谁被谁回来了?

select user, heart
from heart
where (user, heart) in (select heart, user from heart);