我有一张表 my_table
:
id x_id type
--- ---- ----
1 31 a
2 14 b
3 31 c
4 12 c
5 31 b
6 12 c
7 14 a
我想返回 x_id
的 type
满足数组 arr
中所有元素的所有行。
编辑:但是,该数组中的实际值及其数量是未知的,但可能是 type
列的值。 arr
中始终至少有一个值。
所以对于 arr = [b, c]
,我应该得到以下结果:
id x_id type
--- ---- ----
3 31 c
5 31 b
我将如何编写查询以获得这样的结果?
注意:我不是很熟悉 sql
命令,所以如果它没有意义,请帮助我编辑我的问题。
最佳答案
select *
from my_table
where x_id in (select x.x_id
from (select x_id from my_table where type = 'b') x
join (select x_id from my_table where type = 'c') y
on x.x_id = y.x_id)
and type in ('b', 'c')
fiddle 测试: http://sqlfiddle.com/#!2/f8601/2/0
这可能更好地符合变量(有一个变量以“b”、“c”格式保存类型列表,另一个变量保存类型的计数。有什么方法可以让变量保存数组中的值是什么:'b','c'
?
select *
from my_table
where x_id in (select x_id
from my_table
where type in ('b', 'c')
group by x_id
having count(distinct type) = 2)
and type in ('b', 'c')
fiddle : http://sqlfiddle.com/#!2/f8601/12/0
因此,您将使用 2 个 type in ()
点中的变量(()
中的变量)和保存计数的变量代替 2。
关于mysql - 在数组上过滤具有列条件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919604/