我有三个表:stories
,story_types
和comments
以下查询检索stories
表中的所有记录,获取他们的story_types
以及与每个故事相关的评论数量:
SELECT s.id AS id,
s.story_date AS datetime,
s.story_content AS content,
t.story_type_label AS type_label,
t.story_type_slug AS type_slug,
COUNT(c.id) AS comment_count
FROM stories AS s
LEFT OUTER JOIN story_types AS t ON s.story_type_id = t.id
LEFT OUTER JOIN comments AS c ON s.id = c.story_id
GROUP BY s.id;
现在我想做的只是从stories WHERE s.id = 1
(这是主键)检索记录。我尝试了以下内容,但它仍然返回所有记录:
SELECT s.id AS id,
s.story_date AS datetime,
s.story_content AS content,
t.story_type_label AS type_label,
t.story_type_slug AS type_slug,
COUNT(c.id) AS comment_count
FROM stories AS s
LEFT OUTER JOIN story_types AS t ON s.story_type_id = t.id
AND s.id = 1
LEFT OUTER JOIN comments AS c ON s.id = c.story_id
GROUP BY s.id;
我最后还尝试了WHERE
子句,这会引发错误。
在这种情况下,有人能为这样的条件指出正确的语法吗?
我正在使用MySQL 5.1.47。感谢。
答案 0 :(得分:4)
我猜你把GROUP BY放在了WITH后面,这是非法的。有关MySQL中的SELECT语法,请参阅此reference。 试试这个:
SELECT
s.id AS id,
s.story_date AS datetime,
s.story_content AS content,
t.story_type_label AS type_label,
t.story_type_slug AS type_slug,
COUNT(c.id) AS comment_count
FROM
stories AS s
LEFT JOIN story_types AS t ON s.story_type_id = t.id
LEFT JOIN comments AS c ON s.id = c.story_id
WHERE
s.id = 1
GROUP BY
s.id;
编者注:我重新格式化了代码以突出显示查询结构
答案 1 :(得分:1)
对接受的答案发表评论:
对于我而言,这个WHERE将进入第二个JOIN
并不直观
这只是为了概述正确的代码格式如何增强理解。以下是我通常格式化SQL的方法:
SELECT
s.id AS id,
s.story_date AS datetime,
s.story_content AS content,
t.story_type_label AS type_label,
t.story_type_slug AS type_slug,
COUNT(c.id) AS comment_count
FROM
stories AS s
LEFT JOIN story_types AS t ON t.id = s.story_type_id
LEFT OUTER JOIN comments AS c ON s.id = c.story_id
WHERE
s.id = 1
GROUP BY
s.id;
WHERE不在第二个连接上。在SELECT语句中只允许一个WHERE子句,它始终是顶级的。
PS:还要注意,在许多数据库引擎中(除了MySQL),使用GROUP BY子句然后选择列而不通过MIN()
,MAX()
或{等函数聚合它们是非法的。 {1}}。恕我直言,这是一种糟糕的风格和不良习惯。