简体   繁体   中英

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.

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. What if i want to match 50 such values from the table? (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. 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

This problem is called 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,

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

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