如果一个细节符合条件,则mysql获取maser和所有细节

如果一个细节符合条件,则mysql获取maser和所有细节,mysql,Mysql,我有两个表product和specs,如果至少有一个spec与WHERE匹配,我想得到产品和一个组concat(所有specs)。 这是我到目前为止得到的,但它只返回一个与WHERE匹配的规范 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 = 'mi

我有两个表
product
specs
,如果至少有一个spec与WHERE匹配,我想得到产品和一个组concat(所有specs)。 这是我到目前为止得到的,但它只返回一个与WHERE匹配的规范

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


您可以在
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

或者您可以使用
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

两者都给出了结果:

| 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%'

请参见

@user616606唯一的方法是使用
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%'