我有简单的mysql表,包含2个字段:
atr_id | atr_val_id
1 | 100
1 | 200
1 | 300
2 | 100
3 | 100
3 | 200
4 | 200
如何选择具有atr_val_id = 100 AND 200的所有atr_ids值,仅此而已?在这个例子中,这只是atr_id = 3。 或者例如只有200,这将是atr_id = 4
答案 0 :(得分:1)
可能有更简单的方法。这里有一个解决方案,它使用group by,group_contact,distinct,sort和having子句的组合来获取所需的结果
具有atr_val_id = 100 AND 200的所有atr_ids值,仅此而已。这将只返回atr_id = 3
select
atr_id
from
tbl_test
group by
atr_id
having
group_concat(distinct atr_val_id order by atr_val_id asc) = '100,200'
仅200,这将返回atr_id = 4
select
atr_id
from
tbl_test
group by
atr_id
having
group_concat(distinct atr_val_id order by atr_val_id asc) = '200'
答案 1 :(得分:0)
另一种方法是使用下面的NOT EXISTS
select atr_id
from table_name t1
where atr_val_id in(100,200)
AND NOT EXISTS
(
select 1
from table_name t2
where t2.atr_id = t1.atr_id
group by t2.atr_id
having count(t2.atr_val_id) < 2 OR count(t2.atr_val_id) > 2
)
group by t1.atr_id
;
您可以根据您正在查看的atr_val_id的数量更改计数部分。比如说只有200它将成为
having count(t2.atr_val_id) < 1 OR count(t2.atr_val_id) > 1
随后您还需要更改IN子句。