我有两张桌子:
CREATE TABLE Items (id INT, name VARCHAR(8));
CREATE TABLE Likes (item_id INT, usr VARCHAR(8), doeslike BOOLEAN);
INSERT INTO Items VALUES
(1, 'Pen'),
(2, 'Pencil'),
(3, 'Ruler');
INSERT INTO Likes VALUES
(1, 'joe', TRUE ),
(1, 'jill', TRUE ),
(1, 'jack', FALSE),
(2, 'jae', TRUE ),
(2, 'jill', FALSE),
(2, 'john', FALSE),
(2, 'jer', TRUE ),
(3, 'mill', TRUE ),
(3, 'mack', FALSE),
(3, 'moe', TRUE ),
(3, 'gill', TRUE ),
(3, 'zack', FALSE);
在这里小提琴:http://sqlfiddle.com/#!9/d1e0f
我需要一个查询,列出喜欢和不喜欢每件商品的商品和人数,例如:
ITEM LIKES DISLIKES
Pen 2 1
Pencil 2 2
Ruler 3 3
答案 0 :(得分:2)
http://sqlfiddle.com/#!9/d1e0f/2
SELECT Items.* ,
SUM(CASE WHEN Likes.doesLike THEN 1 ELSE 0 END) as likes,
SUM(CASE WHEN Likes.doesLike THEN 0 ELSE 1 END) as dislikes
FROM Items
LEFT JOIN Likes
ON
Items.id = Likes.item_id
GROUP BY Items.id
答案 1 :(得分:2)
您可以使用条件聚合。如果您在select语句中使用SUM(condition)
,那么您将获得该条件为真的次数。像这样在你的桌子上使用它:
SELECT i.name, SUM(l.doeslike = true) AS likes, SUM(l.doeslike = false) AS dislikes
FROM items i
JOIN likes l ON l.item_id = i.id
GROUP BY i.id;
这是一个Fiddle示例。如果有可能存在没有任何喜欢/不喜欢的项目,我还建议使用LEFT JOIN。
答案 2 :(得分:1)
SELECT
I.name AS 'ITEM'
,SUM(CASE WHEN L.doeslike = 1 THEN 1 ELSE 0 END) AS 'LIKES'
,SUM(CASE WHEN L.doeslike = 0 THEN 1 ELSE 0 END) AS 'DISLIKES'
FROM ITEMS I
INNER JOIN LIKES L
ON I.ID = L.ITEM_ID
GROUP BY I.id

答案 3 :(得分:0)
这样的事情可能会满足您的需求:
SELECT count('Likes.usr') as Likes, Items.name AS Product FROM Likes LEFT OUTER JOIN Items ON Items.id = Likes.item_id GROUP BY Product
最好的问候。
答案 4 :(得分:0)
使用LEFTJOIN连接表,然后将布尔字段计数到 得到喜欢和不喜欢
select a.name as ITEM,SUM(CASE WHEN b.doesLike THEN 1 ELSE 0 END) as LIKES ,
SUM(CASE WHEN b.doesLike THEN 0 ELSE 1 END) as DISLIKES from Item a left join Likes b a.id = b.item_id
GROUP BY a.id