我在向查询添加COUNT时遇到问题。
查询工作正常但是只要我添加 COUNT(*)AS totalNum ,我就会得到1个结果每个表
$query = "(SELECT 'table1' AS tablename, navid, thumb, title, longText, clicks AS allClicks, COUNT(*) AS totalNum
FROM table1
WHERE $column=1
AND enabled=1)
UNION DISTINCT
(SELECT 'table2' AS tablename, navid, thumb, title, longText, clicks AS allClicks, COUNT(*) AS totalNum
FROM table2
WHERE $column=1
AND enabled=1)
ORDER BY allClicks DESC";
while ($row = mysql_fetch_assoc($result)){
$navid = $row['navid'];
$thumb = $row['thumb'];
$tablename = $row['tablename'];
$title = strtoupper($row['title']);
etc...
}
问题:在我的加入查询中添加 count(*)的最佳方法是什么?
答案 0 :(得分:1)
使用聚合函数(例如COUNT
)时,需要包含GROUP BY
子句:
(SELECT
'table1' AS tablename,
navid,
thumb,
title,
longText,
clicks AS allClicks,
COUNT(*) AS totalNum
FROM table1
WHERE
$column=1
AND enabled=1
GROUP BY navid, thumb, title, longText, clicks)
UNION DISTINCT
(SELECT
'table2' AS tablename,
navid,
thumb,
title,
longText,
clicks AS allClicks,
COUNT(*) AS totalNum
FROM table2
WHERE
$column=1
AND enabled=1
GROUP BY navid, thumb, title, longText, clicks)