2012-04-05 10 views
2

Ich habe ein Problem COUNT zu meiner Abfrage hinzufügen.
die Abfrage funktioniert gut, aber sobald ich COUNT (*) AS totalNum
i aus jeder Tabelle bekommt 1 Ergebnismysql COUNT mit UNION PHP

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

} 

Frage hinzufügen: Was ist der beste Weg, count (*) in hinzufügen meine meine beitreten Frage?

Antwort

1

Wenn eine Aggregatfunktion, wie COUNT verwenden, müssen Sie eine GROUP BY Klausel enthalten:

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

wenn ich die COUNT, würde dies tun es in der while-Schleife bekommen wollte? $ totalNum = $ row ['totalNum']; –

+0

Ich habe nie eine einzige PHP-Zeile geschrieben ... aber ja, das sieht so aus, als müsste es funktionieren. –

+0

Ich erhalte immer ein Zählergebnis von 1 –