简体   繁体   中英

Select rows in one table based on an id that appears in a column on a different table AND have multiple matches based on another column

This is a very difficult question for me to formulate so the title may need review. But here's my situation:

I need to select all rows from the node table that contain a row in the field_data_field_incident_type where the entity_id matches nid and multiple field_incident_type_tid's which have the same entity_id as the nid. This is some example data from the tables 在此处输入图片说明

For example a query I might want to do is Select all nodes from node that have both field_incident_type_tid of 66 and 64 which should return the rows with the nid 98603 and 98612 from the node table. Right now I'm doing it with left joins like this

SELECT nid
FROM node
left JOIN field_data_field_incident_type field_data_field_incident_type
    ON node.nid = field_data_field_incident_type.entity_id
left JOIN field_data_field_incident_type field_data_field_incident_type_2
    ON field_data_field_incident_type_2.entity_id = node.nid
 WHERE field_data_field_incident_type.field_incident_type_tid = 66
   AND field_data_field_incident_type_2.field_incident_type_tid = 64
;

this does work but that join is creating every permutation of incident_type_tid's and gets crazy if I keep on adding more incident_type_tid requirements Is there a better way to do this?

The standard approach looks like this:

SELECT c.olumns
     , y.ou
     , a.ctually
     , w.ant
  FROM node c
  JOIN field_data_field_incident_type y
    ON y.entity_id = c.nid 
 WHERE y.field_incident_type_tid IN(66,64)
 GROUP 
    BY c.nid 
HAVING COUNT([DISTINCT] y.field_incident_type_tid) = 2 -- WHERE '2' is equal to the number of arguments in IN().

Please keep any comments about syntax errors to yourself.

选择不同的节点。*,field_data_field_incident_type.field_incident_type_tid FROM节点JOIN field_data_field_incident_type field_data_field_incident_type ON node.nid = field_data_field_incident_type.entity_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM