1

我有 3 个表(用户、项目、userlike)和 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

谢谢

4

3 回答 3

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;

样本输出:

| 项目 | 用户名 | 姓名 | 喜欢 |
|--------|--------|--------|--------|
| 2 | 4 | 用户4 | 1 |
| 1 | 7 | 用户7 | 0 |

这是SQLFiddle演示

于 2013-09-14T02:22:20.610 回答
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
于 2013-09-14T02:55:30.223 回答
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
于 2013-09-14T02:13:59.097 回答