让我们考虑我想在SQL语句中使用Users.image
和Users.description
作为表达式,如何添加它们?
如果在SQL语句中添加Users.image
并进行分组,则会出现错误。
这有效:
SELECT
Users.username, COUNT(Topic.userid) AS upvotes
FROM
Users, Role, Topic, Vote, Topic_Vote
WHERE
Users.username = 'Adrian'
AND Users.roleid = Role.roleid
AND Topic.topicid = Topic_Vote.topicid
AND Vote.voteid = Topic_Vote.voteid
AND Topic.userid = Users.userid
GROUP BY
Users.username
这是行不通的:
SELECT
Users.username, Users.image, COUNT(Topic.userid) AS upvotes
FROM
Users, Role, Topic, Vote, Topic_Vote
WHERE
Users.username = 'Adrian'
AND Users.roleid = Role.roleid
AND Topic.topicid = Topic_Vote.topicid
AND Vote.voteid = Topic_Vote.voteid
AND Topic.userid = Users.userid
GROUP BY
Users.username, Users.image
答案 0 :(得分:0)
戈登是正确的,“旧样式”联接存在许多逻辑问题和局限性。 我想您正在寻找类似以下内容的内容-请注意,我没有修复您的原始语法,
WITH UserCounts AS
(
SELECT Users.username, COUNT(Topic.userid) as upvotes
FROM Users, Role, Topic, Vote, Topic_Vote
WHERE Users.username = 'Adrian'
AND Users.roleid = Role.roleid
AND Topic.topicid = Topic_Vote.topicid
AND Vote.voteid = Topic_Vote.voteid
AND Topic.userid = Users.userid
GROUP BY Users.username
)
SELECT UC.*, U.Image
FROM UserCounts AS UC INNER JOIN Users AS U ON UC.UserName = U.UserName