2013-02-06 23 views
0

我有兩個表productspecs我想獲得產品和group_concat(所有規格),如果至少有一個規格匹配的地方。 這是我到目前爲止,但它只返回匹配WHERE的一個規範。mysql得到maser和所有細節,如果一個細節匹配條件

select p.ID, p.name, p.manufacturer GROUP_CONCAT(s.specValue order by s.pID,',') 
from product as p 
JOIN spec AS s ON p.ID = s.pID 
WHERE s.specValue = 'micro' 
group by p.ID 

product table 
| ID | name | manufacturer | 
| 1 | Iphone | apple  | 
| 2 | galaxy | samsung | 
| 3 | note | samsung | 
------------------------------ 
spec table 
| ID | pID | specName | specVlaue | 
| 1 | 1 | charger | bad  | 
| 2 | 2 | charger | micro | 
| 3 | 2 | keypad | touch | 
| 4 | 4 | charger | micro | 
----------------------------------- 

回答

1

您可以使用該WHERE子句中使用IN如下:

select p.ID, 
    p.name, 
    p.manufacturer, 
    GROUP_CONCAT(s.specValue order by s.pID,',') AllSpecs 
from product as p 
JOIN spec AS s 
    ON p.ID = s.pID 
WHERE p.ID in (select pID 
       from spec s1 
       where s1.specValue = 'micro') 
group by p.ID 

SQL Fiddle with Demo

或者你可以使用EXISTS

select p.ID, 
    p.name, 
    p.manufacturer, 
    GROUP_CONCAT(s.specValue order by s.pID,',') AllSpecs 
from product as p 
JOIN spec AS s 
    ON p.ID = s.pID 
WHERE exists (select pID 
       from spec s1 
       where s1.specValue = 'micro' 
       and p.ID = s1.pid) 
group by p.ID 

SQL Fiddle with Demo

均可以得到結果:

| ID | NAME | MANUFACTURER | ALLSPECS | 
-------------------------------------------- 
| 2 | galaxy |  samsung | touch,micro | 

如果你不想使用子查詢,你可以使用HAVING子句用以下值過濾記錄:

select p.ID, 
    p.name, 
    p.manufacturer, 
    GROUP_CONCAT(s.specValue order by s.pID,',') AllSpecs 
from product as p 
JOIN spec AS s 
    ON p.ID = s.pID 
group by p.ID 
having GROUP_CONCAT(s.specValue order by s.pID,',') like '%micro%' 

SQL Fiddle with Demo

+0

@ user616606的唯一方法是使用'HAVING'條款 - 看到這個演示 - http://sqlfiddle.com/#!2/b7dac/16 – Taryn

+0

作品!謝謝@bluefeet – Josh

+0

@ user616606高興地幫忙,很高興你能工作。 :) – Taryn