好的,我有两个MySQL表;一个称为users
,另一个称为likes
。
用户表
id name
----- ------
1 Mark
2 John
3 Paul
4 Dave
5 Chris
喜欢表格
liked_by liked match_id
----- ------ --------
1 2 1
2 1 2
1 3 3
2 3 4
1 5 5
5 1 6
我能够成功加入两个表,如下所示
SELECT users.id, likes.*
FROM users
JOIN likes
ON users.id = likes.liked
但是,我不确定如何格式化WHERE
子句以便返回以下行。
name liked_by liked match_id
------ ------- -------- --------
Mark 1 3 3
John 2 3 4
正如您所看到的,我正在尝试返回Mark和John都喜欢同一个用户的行。在这种情况下,它是用户3,或保罗。我尝试将以下子句添加到查询中,但它显然不起作用。
WHERE (likes.liked_by = '1' OR likes.liked_by = '2')
答案 0 :(得分:2)
找到有多行的喜欢(喜欢?)?否则它只是一个内部联接:
select *
from Likes as l inner join Users as u on u.id = l.liked_by
where liked in (
select liked
from Likes
--where liked_by in (:userid1, :userid2) /* optional: specific pair of users */
--where liked (:userid1, :userid2) /* optional: specific likee */
group by liked
having count(*) > 1
)
我听到很多in
子查询不能很好地优化MySQL。由于分组将保证一对一的关系,因此很容易将其转换为派生表/内联视图/嵌套视图中的内部联接或者您称之为的任何内容。
答案 1 :(得分:1)
您需要自己加入likes
表格,以获取喜欢特定用户的用户对列表。查询非常简单。
测试数据:
CREATE TABLE users (id INT, name VARCHAR(100));
INSERT INTO users(id, name) VALUES (1,'Mark'), (2,'John'), (3,'Paul'), (4,'Dave'), (5,'Chris');
-- Note: I assumed that match_id is a primary key
CREATE TABLE likes (match_id INT PRIMARY KEY AUTO_INCREMENT, liked_by INT, liked INT);
INSERT INTO likes(liked_by, liked) VALUES (1,2), (2,1), (1,3), (2,3), (1,5), (5,1);
实际查询:
SELECT CONCAT(user1.name, ' and ', user2.name, ' like ', user3.name) AS `Readable result`
-- join the likes table with itself where two users like the same user
FROM likes AS like1
INNER JOIN likes AS like2 ON like1.liked = like2.liked AND
like1.match_id < like2.match_id
-- join the result with user table three times to obtain names of all users involved
INNER JOIN users AS user1 ON like1.liked_by = user1.id
INNER JOIN users AS user2 ON like2.liked_by = user2.id
INNER JOIN users AS user3 ON like1.liked = user3.id
结果:
+--------------------------+
| Readable result |
+--------------------------+
| Mark and John like Paul |
| John and Chris like Mark |
+--------------------------+