简体   繁体   中英

mysql COUNT with UNION php

i am having a problem adding COUNT to my query.
the query works fine but as soon as i add COUNT(*) AS totalNum
i get 1 result from each table

$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...

}

question: what is the best way to add count(*) into my my join query?

When using an aggregate function, such as COUNT , you need to include a GROUP BY clause:

(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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM