gpt4 book ai didi

MySQL - 同一查询中的 COUNT 和 MAX。 MAX 忽略 WHERE 子句

转载 作者:行者123 更新时间:2023-11-29 19:15:49 25 4
gpt4 key购买 nike

我正在执行以下脚本:

SELECT  a.*,
gg.image as 'recent_image_file'
FROM

( SELECT c.cid,
c.category_name AS 'cat_name',
COUNT(g.id) AS image_count,
c.category_image AS 'images',
c.estgendpref,
MAX(n.id) as 'recent_image'
FROM tbl_category c
LEFT JOIN tbl_gallery_category g
ON c.cid=g.cat_id
LEFT JOIN tbl_gallery n
ON n.id=g.image_id

WHERE n.date_active < NOW()
GROUP BY c.cid
ORDER BY c.category_name ASC
) a

INNER JOIN tbl_gallery gg
ON a.recent_image = gg.id;

一切都返回正常,除了 MAX(n.id) 忽略 WHERE 子句并返回类别的顶级 id。如何让 MAX(n.id) 返回包含 WHERE 子句的结果集的最大值?谢谢。

最佳答案

您应该在 on 子句中使用 where 条件,添加适当的 AND .. 否则,where 将用作内连接条件

SELECT  a.*,
gg.image as 'recent_image_file'
FROM

( SELECT c.cid,
c.category_name AS 'cat_name',
COUNT(g.id) AS image_count,
c.category_image AS 'images',
c.estgendpref,
MAX(n.id) as 'recent_image'
FROM tbl_category c
LEFT JOIN tbl_gallery_category g ON c.cid=g.cat_id
LEFT JOIN tbl_gallery n ON n.id=g.image_id and n.date_active < NOW()
GROUP BY c.cid
ORDER BY c.category_name ASC
) a

INNER JOIN tbl_gallery gg
ON a.recent_image = gg.id;

关于MySQL - 同一查询中的 COUNT 和 MAX。 MAX 忽略 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42726888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com