简体   繁体   English

MySQL基于同一表中的多行选择行

[英]Mysql select row based on multiple rows in same table

I have the following table structure: 我具有以下表结构:

item_id  | value |  
==================  
1        |   1   |  
1        |   3   |  
1        |   4   |  
2        |   2   |  
2        |   3   |  
2        |   4   |  
2        |   5   |  
3        |   1   |  
3        |   5   |  
3        |   6   |  
4        |   1   |  
4        |   3   |  
4        |   4   |  
4        |   5   |

I have a query that returns those item_id whose value matches with 1, 3 and 4. So here, the item_ids that should be returned are 1 and 4. 我有一个查询,返回的值与1、3和4匹配的item_id。因此,在这里,应返回的item_id为1和4。

My query: 我的查询:

select item_id from table t
where exists (select item_id from table t1 where value = 1 and t1.item_id = t.item_id)
and exists (select item_id from table t1 where value = 2 and t1.item_id = t.item_id) group by item_id

This query is working fine. 此查询工作正常。 Here i am matching only 3 values. 在这里,我只匹配3个值。 What if i want to match 50 such values from the table? 如果我要匹配表中的50个此类值怎么办? (all the 50 values are stored in a php array) The query will be huge and also i want to do the same thing from two different tables in the same query. (所有的50个值都存储在一个php数组中)查询将是巨大的,并且我也想从同一查询中的两个不同表中执行相同的操作。 So, this will double the size of an already huge query. 因此,这将使已经很庞大的查询的大小增加一倍。 Please suggest me some other way around. 请提出其他建议。

Edited:: 编辑::

table 2
--------

item_id  | user_id |  
==================  
1        |   1   |  
1        |   5   |  
1        |   7   |  
2        |   2   |  
2        |   3   |  
2        |   4   |  
2        |   5   |  
3        |   1   |  
3        |   5   |  
3        |   6   |  
4        |   1   |  
4        |   3   |  
4        |   4   |  
4        |   5   |

Now, i want item_id where values from table1 are 1,3,4 and user_id from table2 are 1,5,7 现在,我想要item_id,其中table1的值为1,3,4,user_id来自table2的为1,5,7

This problem is called Relational Division . 这个问题称为Relational Division

SELECT  item_ID
FROM    tableName
WHERE   value IN (1,3,4)
GROUP   BY item_ID
HAVING  COUNT(*) = 3

if uniqueness was not enforce on column value for every item_id , DISTINCT is required to count only unique values, 如果不是对每个item_idvalue都未强制唯一性,则要求DISTINCT仅计算唯一值,

SELECT  item_ID
FROM    tableName
WHERE   value IN (1,3,4)
GROUP   BY item_ID
HAVING  COUNT(DISTINCT value) = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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