【发布时间】:2017-01-25 19:39:50
【问题描述】:
我遇到了一些问题。 我尝试计算类别和子类别中的所有文章。
我使用这个查询:
SELECT
cat.*, COUNT(art.id) AS total
FROM
article_categories cat
LEFT JOIN
article_categories c2 ON (c2.category_parent = cat.category_id)
LEFT JOIN
articles art ON (art.cid = cat.category_id
OR art.cid = c2.category_id)
WHERE
cat.category_parent = 0 AND art.st = 1
AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22),
TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120,
art.cid)
GROUP BY IF(c2.category_parent > 0,
c2.category_parent,
cat.category_id)
ORDER BY cat.category_order ASC
但对于某些类别,总数 = 36355
当我使用这个查询时:
SELECT
*
FROM
`articles`
WHERE
st = 1
AND cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22)
AND IF(cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22),
TO_DAYS(CURDATE()) - TO_DAYS(date_edit) < 120,
cid)
总计 = 7730
我做错了什么?
我的桌子:
articles:
- id
- cid
- title
- date_add
- date_edit
- st
article_categories
- category_id
- category_name
- category_order
- category_parent
感谢您的帮助
[编辑]
$sql1 = "SELECT cat.*, COUNT(art.id) AS total FROM article_categories cat LEFT JOIN articles art ON (art.cid = cat.category_id) WHERE cat.category_parent = 0 AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22), TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120, art.cid) GROUP BY art.cid";
$category = array();
foreach ($row as $cat) {
$total = $cat['total'];
$sql2 = "SELECT cat.*, COUNT(art.id) AS total FROM article_categories cat LEFT JOIN articles art ON (art.cid = cat.category_id) WHERE cat.category_parent = ".$cat['category_id']." AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22), TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120, art.cid) GROUP BY art.cid";
foreach ($row2 as $cat2) {
$total += $cat2['total'];
}
$category[] = array('category_id'=> $cat['category_id'], 'total' => $total);
}
【问题讨论】:
-
您期待什么以及为什么?
-
我想显示主要类别并与文章一起计数(包含子类别中的所有文章)
-
你的问题是什么?你期待不同的结果吗?
-
问题是某些类别的第一次查询计数36355条记录但应该计数7730
-
您能否解释一下为什么您希望得到这个结果?