sql - Mysql select row based on multiple rows in same table -
i have 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 query returns item_id value matches 1, 3 , 4. here, item_ids should returned 1 , 4.
my query:
select item_id table t exists (select item_id table t1 value = 1 , t1.item_id = t.item_id) , exists (select item_id table t1 value = 2 , t1.item_id = t.item_id) group item_id
this query working fine. here matching 3 values. if want match 50 such values table? (all 50 values stored in php array) query huge , want same thing 2 different tables in same query. so, double size of huge query. please suggest me 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, want item_id values table1 1,3,4 , user_id table2 1,5,7
this problem called relational division
.
select item_id tablename value in (1,3,4) group item_id having count(*) = 3
if uniqueness not enforce on column value
every item_id
, distinct
required count unique values,
select item_id tablename value in (1,3,4) group item_id having count(distinct value) = 3
Comments
Post a Comment