将其更改为AND
not a WHERE
:
SELECT p.id, p.username, p.date, p.subject, p.year, p.brand,
p.model, p.type, p.bodywork, p.text, p.image, p.chassis, COUNT(c.id) AS answers
FROM posts_tbl AS p
LEFT JOIN post_reply_tbl AS c
ON c.post_id = p.id
AND c.type = 1 AND c.type = 3
LEFT JOIN post_reply_tbl AS a
ON a.post_id = p.id
AND a.type = 2
GROUP BY p.id
我认为你需要稍微改变一下,因为c.type
不能同时有两个值:
SELECT p.id, p.username, p.date, p.subject, p.year, p.brand,
p.model, p.type, p.bodywork, p.text, p.image, p.chassis, COUNT(c.id) AS answers
FROM posts_tbl AS p
LEFT JOIN post_reply_tbl AS c
ON c.post_id = p.id
AND c.type IN (1, 3) -- changed to use an OR
LEFT JOIN post_reply_tbl AS a
ON a.post_id = p.id
AND a.type = 2
GROUP BY p.id
如果您希望c.type
等于1
和3
,那么您可能需要考虑使用:
SELECT p.id, p.username, p.date, p.subject, p.year, p.brand,
p.model, p.type, p.bodywork, p.text, p.image, p.chassis, c.answers
FROM posts_tbl AS p
LEFT JOIN
(
select COUNT(c.id) answers, c.post_id
from post_reply_tbl c
where c.type in (1, 3)
group by c.post_id
having COUNT(distinct type) = 2
) AS c
ON c.post_id = p.id
LEFT JOIN post_reply_tbl AS a
ON a.post_id = p.id
AND a.type = 2
只是对查询的后续说明,因为您GROUP BY
只在一个列上使用 a,MySQL 决定返回其他列的哪些值并且这些值可能是意外的。您可以确定返回值的唯一方法是按它们聚合每个列或组。(参见MySQL 对 GROUP BY 的扩展)
来自 MySQL 文档:
MySQL 扩展了 GROUP BY 的使用,以便选择列表可以引用未在 GROUP BY 子句中命名的非聚合列。...您可以使用此功能通过避免不必要的列排序和分组来获得更好的性能。但是,这主要在每个未在 GROUP BY 中命名的非聚合列中的所有值对于每个组都相同时很有用。服务器可以从每个组中自由选择任何值,因此除非它们相同,否则选择的值是不确定的。此外,从每个组中选择值不会受到添加 ORDER BY 子句的影响。在选择了值之后对结果集进行排序,并且 ORDER BY 不会影响服务器选择的值。
出于这个原因,最好使用子查询来获取,count()
然后您将确保您为其余列返回正确的结果。:
SELECT p.id, p.username, p.date, p.subject, p.year, p.brand,
p.model, p.type, p.bodywork, p.text, p.image, p.chassis, c.answers
FROM posts_tbl AS p
LEFT JOIN
(
select COUNT(c.id) answers, c.post_id
from post_reply_tbl c
where c.type in (1, 3)
) AS c
ON c.post_id = p.id
LEFT JOIN post_reply_tbl AS a
ON a.post_id = p.id
AND a.type = 2