我在数据库中有两个表:
Article
--------------------------------------------
articleID INTEGER PRIMARY KEY AUTOINCREMENT
userID VARCHAR
Rating
--------------------------------------------
articleID INTEGER
userID VARCHAR
rating INTEGER
示例数据:
Article
articleID userID
---------------------------------
1 12345
2 23456
3 23456
4 99999
5 15678
Rating
articleID userID rating
--------------------------------------------
1 12345 7.5
2 12345 8.5
2 31359 7.5
1 24021 0.0
1 25012 7.5
我想获得所有文章并展示我是否对它们进行了评分。我试过了,我只能通过这个声明获得带有评级文章的列表:
SELECT a.*, rating AS myRating FROM Article AS a
LEFT JOIN Rating AS b
ON a.articleID = b.articleID
WHERE (b.userID is NULL || b.userID = "12345")
如何加入表格以获得结果?
Expected output (with userID 12345)
articleID userID myRating
--------------------------------------------
1 12345 7.5
2 23456 8.5
3 23456 NULL
4 99999 NULL
5 15678 NULL
答案 0 :(得分:4)
WHERE子句将过滤掉userID不是12345或NULL ...
的列SELECT a.*, rating AS myRating
FROM Article AS a
LEFT JOIN Rating AS b
ON a.articleID = b.articleID
AND b.userID = "12345"
由于您要显示a的所有行,请将用户ID限制放在ON
子句中。现在它将从A获取所有行,如果用户标识不是12345,则为NULL评级。
答案 1 :(得分:1)
你的意思是,
SELECT a.*, b.rating AS myRating
FROM Article AS a
LEFT JOIN Rating AS b ON(a.articleID = b.articleID AND b.userID = "12345")