如何构造一个返回结果的MySql查询,该结果包含数组中的所有值?

时间:2014-03-20 06:36:52

标签: mysql

我的MySql查询看起来像

SELECT * FROM node as nd
LEFT JOIN term_node as trm_nd ON trm_nd.nid = nd.nid
WHERE nd.title = 'Gadget - definition' 
AND nd.type = 'help_system' 
AND trm_nd.tid IN (434, 456, 25, 293)

返回结果

-------------------------------------------------------
nid     title                   type           tid
-------------------------------------------------------
26986   Gadget - definition     help_system     25
26986   Gadget - definition     help_system     293
52421   Gadget - definition     help_system     25
52421   Gadget - definition     help_system     293
73061   Gadget - definition     help_system     25
73061   Gadget - definition     help_system     293
86071   Gadget - definition     help_system     25
86071   Gadget - definition     help_system     293
98596   Gadget - definition     help_system     25
98596   Gadget - definition     help_system     293
98596   Gadget - definition     help_system     434
98596   Gadget - definition     help_system     456

但我需要的结果类似下面的一个,需要返回一个nid与tid列中所有数组值(434,456,25,293)相关联的值

-------------------------------------------------------
nid     title                   type           tid
-------------------------------------------------------
98596   Gadget - definition     help_system     25
98596   Gadget - definition     help_system     293
98596   Gadget - definition     help_system     434
98596   Gadget - definition     help_system     456

1 个答案:

答案 0 :(得分:1)

在现有查询中使用GROUP BY并将其设为子查询,如下所示:

SELECT * FROM
node n1
JOIN (
  SELECT nid FROM node as nd
  LEFT JOIN term_node as trm_nd ON trm_nd.nid = nd.nid
  WHERE nd.title = 'Gadget - definition' 
  AND nd.type = 'help_system' 
  AND trm_nd.tid IN (434, 456, 25, 293)
  GROUP BY nid
  HAVING (COUNT(DISTINCT tid)) = 4
) t1
ON n1.nid = t1.nid