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 に答える