2016-10-17 5 views
0

Ich habe drei Tabelleninhalt Informationen über BeiträgeMYSQL: select count mit Union drei Tabellen

und jede Tabelle hat post_id es ist foreign_key für Beitrag Tisch

first table = `likes` 
second table = `Comment` 
and last one = `Visitor` 

jede Tabelle ein paar Informationen über die Nutzer wie Sitzung hat oder id und etc

ich brauche neue view-Tabelle enthalten Post-ID und die Anzahl der Besucher erstellen, mag, Kommentar

ich habe versucht, diese

SELECT * 


    from (

select id , count(id) as Comment 
from Post left join Comment on id = Post_id 
group by id 

    UNION 

select id, count(id) as Visitor  
from Post left join Visitor on id = Post_id 
group by id 
UNION 

select id, count(id) as Likes 
from Post left join Likes on id = Post_id 
group by id 

) CountsTable 
GROUP BY CountsTable.id 

aber es hat nicht funktioniert. ich weiß nicht, warum das Ergebnis nur die erste innere select ist

in meinem Beispiel das Ergebnis

ist
| id | Comment| 
|--------|------- | 
| 1 | 55 |  
| 2 | 25 | 
| 3 | 12 | 

ich etwas erwarten, wie die

| id | Comment | Likes | Visitor | 
|--------------|-------|---------| 
| 1 | 55 | 100 | 2000 |  

Antwort

0

Keine Notwendigkeit UNION zu verwenden. Zählen Sie die Datensätze für jeden Post in allen drei Tabellen und LEFT JOIN Ergebnis mit Post Tabelle

Probieren Sie etwas wie diese

+0

arbeitete für mich danke, aber wenn ich versuchte, Blick von diesem zu machen ich habe „Ansicht SELECT eine Unterabfrage in der FROM-Klausel enthält“ – isams

0

Sie es mit einer Left Join Abfrage tun können, zum Beispiel:

select u.id, count(distinct l.id) as likes, count(distinct c.id) as comments 
from user u left join likes l on u.id = l.user_id 
left join comments c on u.id = c.user_id 
group by u.id; 

Hier ist SQL Fiddle.

+0

es hat nicht # 1054 arbeiten - Unknown column ‚l.id‘ in 'Feldliste' – isams

+0

Überprüfen Sie den Spaltennamen in der Likes-Tabelle. Überprüfen Sie auch mein create-Tabellenskript in SQL Fiddle. –

0
SELECT id, SUM(Comment),SUM(Visitor),SUM(Likes) from (

select id , count(id) as Comment, 0 as Visitor, 0 as Likes 
from Post left join Comment on id = Post_id 
group by id 

UNION ALL 

select id, 0 as Comment, count(id) as Visitor , 0 as Likes  
from Post left join Visitor on id = Post_id 
group by id 

UNION ALL 

select id, 0 as Comment, 0 as Visitor, count(id) as Likes 
from Post left join Likes on id = Post_id 
group by id 

) CountsTable 
GROUP BY CountsTable.id