gpt4 book ai didi

php - 从表和引用表中选择列、count(id)

转载 作者:行者123 更新时间:2023-11-30 22:36:23 25 4
gpt4 key购买 nike

我有一个查询,我想从两个表(一个父表和一个引用表)中获取列,并选择引用表上每个帖子的类别总数

文章

id
title
poster
pdate
content

类别

id
name

cats_rel(带外键约束的关系表)

id
pid
cat_id

我想获取具有一个类别 ID 和每个帖子的类别总数的帖子列表。

我用它来获取所需的数据,但速度很慢。有没有更好的方法可以更快地获得它?

SELECT cc.id, title, poster, pdate, content, js.pid, js.sno 
FROM articles cc LEFT JOIN
(SELECT pid, cat_id, count(cat_id) as sno FROM cats_rel GROUP BY pid)js
ON js.pid = cc.id WHERE cc.status='approved' ORDER BY cc.id DESC

最佳答案

您不需要内部查询。

SELECT cc.id, title, poster, pdate, content, js.pid, count(js.cat_id) as sno 
FROM articles wp
LEFT JOIN cats_rel js ON js.pid = cc.id
WHERE wp.status='approved'
group by cc.id, title, poster, pdate, content, js.pid
ORDER BY cc.id DESC

关于php - 从表和引用表中选择列、count(id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442003/

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