2

我在数据库中有两个表:

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
4

2 回答 2

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 获取所有行,如果用户 ID 不是 12345,则使用 NULL 进行评级。

于 2012-07-05T06:45:13.530 回答
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")
于 2012-07-05T06:46:25.457 回答