“IN”子句中的多个内联变量

时间:2012-08-27 09:33:19

标签: mysql sql

我有一个表格,其中所有数据都按行存储。

key      name   field   value
11       sam    state   1
11       fred   state   1
21       sam    state   3
21       fred   state   1
11       sam    dist    1
11       fred   dist    1
21       sam    dist    1
21       fred   dist    1

我需要一个查询来获取"name" having dist = 1 with state = 1的数量。

以下内容......     选择计数(值)     从表     where field ='dist'     和值= 1     和键,名称(从表中选择键,名称,其中field ='state'和value = 1)

在上面的示例中,我希望答案为“3”(带键= 21的山姆不符合条件)。

3 个答案:

答案 0 :(得分:0)

试试这个:

select count (value) 
from table a
where  field = 'dist' 
and value = 1 
and exists
(
  select 1 from table n where field = 'state' and value =1
  and a.key = b.key 
  and a.name = b.name
)

答案 1 :(得分:0)

select count(distinct yourtable.name)
from yourtable
inner join
(
    select key, name from yourtable
    where field='dist' and value = 1
) dist1
    on yourtable.key = dist1.key 
    and yourtable.name = dist1.name
where field='state' and value = 1

答案 2 :(得分:0)

使用联接:

select count(distinct key, name) from table t1
inner join table t2
  on t2.key = t1.key and t2.name = t1.name and t2.field = 'state' and t2.value = 1
where t1.field = 'dist' and t1.value = 1