Reputation: 4693
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?
Upvotes: 2
Views: 589
Reputation: 37388
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)
Upvotes: 1