2017-07-06 3 views
0

, wenn ich diese beiden Tabellen haben:aus, und alle Zeilen in einer anderen Tabelle

[ id -  title -  content ] 
[ 1 -  title1 -  content1 ] 
[ 2 -  title2 -  content2 ] 

und

[ id -  pid -  tags ] 
[ 1 -  1 -  TAG1 ] 
[ 2 -  1 -  TAG2 ] 
[ 3 -  1 -  TAG3 ] 
[ 4 -  2 -  TAG2 ] 

Nun, was ich versuche, die title zu tun ist, wählen und content von table1 dann alle tags von table2 wo b.pid = a.id

so meine Frage ist

SELECT a.title, a.content, b.tags 
FROM table1 a LEFT JOIN table2 b ON a.id = b.pid 
WHERE a.id = 1 

, was ich will bekommen, ist

title1 content1 TAG1 TAG2 TAG3

aber was ich bekommen ist nur TAG1 und wiederholte Werte von title1 content1 für jeden Tag

Dann habe ich versucht,

SELECT a.title, a.content, 
(SELECT DISTINCT b.tags) 
    FROM table1 a LEFT JOIN table2 b 
    WHERE a.id = 1 

funktionieren aber immer noch nicht wie beabsichtigt.

+0

Sie haben zwei _tables_, nicht _databases_. – jarlh

+0

@jarlh ich "behoben", dass beim Ändern der Codezeilen in Blöcke –

Antwort

2

Für ibtain die Tags zu ID auf der gleichen Zeile im Zusammenhang könnten Sie Group_concat verwenden

select a.title, a.content, group_concat(b.tags) 
    from table1 a LEFT JOIN table2 b ON a.id = b.pid 
    WHERE a.id = 1 
    group by a.title, a.content 

Sie zählen auf derselben Abfrage zu

select a.title, a.content, group_concat(b.tags), count(*) 
    from table1 a LEFT JOIN table2 b ON a.id = b.pid 
    WHERE a.id = 1 
    group by a.title, a.content 

für verschiedene tas verwenden können, können Sie verwenden

select a.title, a.content, group_concat(distinct b.tags) 
    from table1 a LEFT JOIN table2 b ON a.id = b.pid 
    WHERE a.id = 1 
    group by a.title, a.content 
+0

für den Fall, dass ich 'COUNT()' für alle Tags verwenden möchten, hat es die gleiche Eigenschaft? –

+0

Ja können Sie zählen (*) tooo .. Antwort aktualisiert – scaisEdge

+2

Antwort aktualisiert ..but Hinzufügen von Anfrage Schritt für Schritt ist nicht fair ..once und Antwort ist crrectly Sie sollten die Antwort akzeptieren und eventaaly eine neue gut dokumentierte Frage – scaisEdge

Verwandte Themen