我正在构建一个允许用户互相推荐音乐的应用程序,并且在构建查询时遇到问题,该查询会返回涉及用户自己以及任何用户朋友的推荐“流” 。这是我的表结构:
建议
ID Sender Recipient [other columns...]
-- ------ --------- ------------------
r1 u1 u3 ...
r2 u3 u2 ...
r3 u4 u3 ...
用户
ID Email First Name Last Name [other columns...]
--- ----- ---------- --------- ------------------
u1 ... ... ... ...
u2 ... ... ... ...
u3 ... ... ... ...
u4 ... ... ... ...
关系
ID Sender Recipient Status [other columns...]
--- ------ --------- -------- ------------------
rl1 u1 u2 accepted ...
rl2 u3 u1 accepted ...
rl3 u1 u4 accepted ...
rl4 u3 u2 accepted ...
因此,对于用户'u4'(谁是'u1'的朋友),我想查询与u4相关的推荐“流”。此流将包括发件人或收件人为u4的所有建议,以及发件人或收件人为u1(朋友)的所有建议。
这是我到目前为止的查询:
SELECT * FROM recommendations
WHERE recommendations.sender IN
( SELECT sender FROM relationships WHERE recipient='u4' AND status='accepted'
UNION
SELECT recipient FROM relationships WHERE sender='u4' AND status='accepted')
OR recommendations.recipient IN
( SELECT sender FROM relationships WHERE recipient='u4' AND status='accepted'
UNION
SELECT recipient FROM relationships WHERE sender='u4' AND status='accepted')
UNION
SELECT * FROM recommendations
WHERE recommendations.sender='u4' OR recommendations.recipient='u4'
GROUP BY recommendations.id
ORDER BY datecreated DESC
据我所知,这似乎有用(我不是SQL专家)。它返回Recommendations表中与给定用户“相关”的所有记录。但是,我现在也无法从Users表中获取数据。 Recommendations表有发件人和收件人的ID(外键),但我也想得到每个人的名字和姓氏。我想我需要某种加入,但我迷失了如何继续,并正在寻求帮助。 (而且,如果有人在我当前的查询中看到任何需要改进的地方,我都会听到。)
谢谢!
答案 0 :(得分:0)
好的,相信我弄清楚了。必须创建2个users表的别名,以便我可以从每个表中拉出来。这是工作查询:
SELECT recommendations.*, user1.firstname AS 'senderFirstName', user1.lastname AS 'senderLastName', user2.firstname AS 'recipientFirstName', user2.lastname AS 'recipientLastName'
FROM (recommendations, users)
INNER JOIN users AS user1 ON (user1.id=recommendations.sender)
INNER JOIN users AS user2 ON (user2.id=recommendations.recipient)
WHERE recommendations.sender IN (SELECT sender FROM relationships WHERE recipient='4' AND status='accepted' UNION SELECT recipient FROM relationships WHERE sender='4' AND status='accepted') OR recommendations.recipient IN (SELECT sender FROM relationships WHERE recipient='4' AND status='accepted' UNION SELECT recipient FROM relationships WHERE sender='4' AND status='accepted')
UNION
SELECT recommendations.*, user1.firstname AS 'senderFirstName', user1.lastname AS 'senderLastName', user2.firstname AS 'recipientFirstName', user2.lastname AS 'recipientLastName'
FROM (recommendations, users)
INNER JOIN users AS user1 ON (user1.id=recommendations.sender)
INNER JOIN users AS user2 ON (user2.id=recommendations.recipient)
WHERE recommendations.sender='4' OR recommendations.recipient='4'
GROUP BY recommendations.id
ORDER BY date created DESC
如果有人发现任何错误或有改进的余地,我会感激任何建议。