为什么这在MySQL中不起作用?
SELECT blogentry.*,
person.personName,
(SELECT *
FROM BlogEntryComment
Where BlogEntryID = '8') as CommentCount
FROM blogentry
INNER JOIN person ON blogentry.personID = person.personID
WHERE blogentry.deleted = 'N'
ORDER BY blogentry.dateAdded DESC
答案 0 :(得分:3)
子查询只需要返回一个值:字段计数。 *
返回所有行,而count(*)
将返回有多少行。
(SELECT count(*) FROM BlogEntryComment Where BlogEntryID = '8')
答案 1 :(得分:1)
你必须使用聚合函数COUNT
来获取值 - 在subSELECT中SELECT *
将是脆弱的,因为它试图将行的所有列值返回到单个列中
也就是说,您所拥有的内容将为返回的每条CommentCount
记录返回相同的BLOGENTRY
值。以下是更好的方法:
SELECT be.*,
p.personname,
COALESCE(x.num, 0) AS CommentCount
FROM BLOGENTRY be
JOIN PERSON p ON p.personid = be.personid
LEFT JOIN (SELECT bec.blogentryid,
COUNT(*) AS num
FROM BLOGENTRYCOMMENT bec
GROUP BY bec.blogentryid) x ON x.blogentryid = be.blogentryid