我有3个表(用户,项目,用户类似)和2个SQL查询。如何统一这两个查询?
SELECT item.userid, item.id, user.name FROM item
INNER JOIN user ON item.userid = user.id
SELECT userid,itemid, COUNT(*) AS `liked` FROM userlike
WHERE userid=9
GROUP BY itemid
我想知道特定用户(9)是否喜欢该项目。
结果应该是这样的
itemid userid name liked* (*whether 'user 9' liked this item or not)
1 7 foo 0
2 4 asd 1
由于
答案 0 :(得分:2)
您想为此
使用OUTER JOIN
SELECT i.id itemid, u.id userid, u.name, COALESCE(liked, 0) liked
FROM item i JOIN user u
ON i.userid = u.id LEFT JOIN
(
SELECT itemid, COUNT(*) liked
FROM userlike
WHERE userid = 9
GROUP BY itemid
) l
ON i.id = l.itemid;
或
SELECT i.id itemid, u.id userid, u.name, l.userid IS NOT NULL liked
FROM item i JOIN user u
ON i.userid = u.id LEFT JOIN userlike l
ON i.id = l.itemid
AND l.userid = 9;
示例输出:
| ITEMID | USERID | NAME | LIKED | |--------|--------|-------|-------| | 2 | 4 | user4 | 1 | | 1 | 7 | user7 | 0 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
SELECT item.id, item.userid, user.name, userlike.liked
FROM item
JOIN user ON user.id = item.userid
JOIN userlike ON item.id = userlike.itemid
WHERE userlike.liked = 1
GROUP BY item.id
或强>
SELECT item.id, item.userid, user.name, userlike.liked
FROM item
JOIN user ON user.id = item.userid
JOIN userlike ON item.id = userlike.itemid
WHERE COUNT(userlike.liked) >= 1
GROUP BY item.id
答案 2 :(得分:0)
您无需使用COUNT
。您只需要知道userlike
表中是否有特定项目和特定用户的条目:
SELECT i.id as itemid, u.id as userid, u.name,
case when ul.userid is null then 0 else 1 end as liked
FROM item i
INNER JOIN user u ON i.userid = u.id
LEFT OUTER JOIN userlike ul ON i.id = ul.itemid AND ul.userid=9
ORDER BY i.id