2016-05-04 26 views
0

Ich habe gegeben worden this great answer, wie verschieden wählen Zeilen aus 3 meiner Datenbanktabellen:MySQL wählen viele Spalten, wenn GROUP_CONCAT mit

select p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT c.c_id SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT s.s_id SEPARATOR ', ') as shops 
from product p inner join product_category c on p.p_id = c.p_id 
       inner join product_shop s on p.p_id = s.p_id 
where c.c_id in (2,8) 
    and s.s_id in (1,2) 
group by p.p_id, p.`p_name`, p.brand 

Ich möchte nur jetzt auf, dass erweitern möchten auch mehr Spalten ausgewählt aus shop und category Tabellen. Ich möchte s.s_name und c.c_name zu den ausgewählten Ergebnissen hinzufügen. Wie würde ich das tun? Ich versuche, mit CONCAT von this answer zB:

GROUP_CONCAT(
    DISTINCT CONCAT(tags.id,',',tags.displayName) 
    ORDER BY posts.id 
    SEPARATOR ';' 
) 

So fügte hinzu, dass in meiner Abfrage nur die category.c_name wie folgt hinzu:

select p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT CONCAT(category.c_id, category.c_name) SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT s.s_id SEPARATOR ', ') as shops 
from product p inner join product_category c on p.p_id = c.p_id 
       inner join product_shop s on p.p_id = s.p_id 
where c.c_id in (2,8) 
    and s.s_id in (1,2) 
group by p.p_id, p.`p_name`, p.brand 

Aber aus irgendeinem Grund, der diesen Fehler geben:

Wie füge ich korrekt mehr Spalten aus Kategorie- und Shop-Tabellen zu meiner ausgewählten Abfrage hinzu?

+0

'category' Tabelle ist nicht in der Join-Klausel meinst du' product_category'? und wenn das der Fall ist, sollte 'CONCAT (c.c_id, c.c_name)' die Aufgabe übernehmen. –

+0

Wenn die Tabelle nicht in der Abfrage ist, dann ist es Spalten gibt es weder – Strawberry

+0

Ich sehe einen Alias ​​für 'Kategorien', nicht' Kategorie'. Haben Sie versucht, 'category' durch' categories' zu ersetzen? – starshine531

Antwort

0

Ich musste die shop und category Tabellen in die Abfrage mit inner join hinzufügen. Die vollständige SQL-Anweisung lautet:

SELECT p.p_id, p.`p_name`, p.brand, 
GROUP_CONCAT(DISTINCT CONCAT(c.c_id,':',c.c_name) SEPARATOR ', ') as categories, 
GROUP_CONCAT(DISTINCT CONCAT(s.s_id,':',s.s_name) SEPARATOR ', ') as shops 
FROM product p 
INNER JOIN product_category pc on p.p_id = pc.p_id 
INNER JOIN category c ON c.c_id = pc.c_id 
INNER JOIN product_shop ps on p.p_id = ps.p_id 
INNER JOIN shop s ON s.s_id = ps.s_id 
WHERE c.c_id in (2,8) 
AND s.s_id in (1,2) 
GROUP BY p.p_id, p.`p_name`, p.brand