2

我在将 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(*)添加到我的联接查询中的最佳方法是什么?

4

1 回答 1

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) 
于 2012-04-05T16:19:26.097 回答