0

2つのテーブルがあり、少なくとも1つの仕様がWHEREに一致する場合は、製品productspecsgroup_concat(すべての仕様)を取得したいと思います。これは私がこれまでに持っているものですが、WHEREに一致する1つの仕様のみを返します。

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    |
-----------------------------------
4

1 に答える 1

1

句でaINを使用する次のものを使用できます。WHERE

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 FiddlewithDemoを参照してください。

または、次を使用できます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 FiddlewithDemoを参照してください

どちらも結果を出します。

| 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 FiddlewithDemoを参照してください

于 2013-02-06T20:09:48.650 に答える