将表与列表联系起来

时间:2012-01-19 09:33:36

标签: mysql sql sqlite

我有一个像这样的值列表:

("UXT8","U61J","U61W","U62U","X82U","U5NF","U635","U526","28FX")

我希望能够从一个表中提取它们在表的一个字段中出现的次数,即使出现次数是0。

我所期待的与

类似
select key_field, count(*) from table
where key_field in ("UXT8","U61J","U61W","U62U","X82U","U5NF","U635","U526","28FX")
group by key_field;

但有一种左连接效果。

这在sql中是否可行,特别是在sqlite或mysql变种中?

由于

5 个答案:

答案 0 :(得分:2)

我会使用union来构建内存表而不是列表:

select t.code, count(mytable.unique_id) from 
  (
  select 'UXT8' as code union 
  select 'U61J' as code union 
  select 'U61W' as code union 
  select 'U62U' as code union 
  select 'X82U' as code union 
  select 'U5NF' as code union 
  select 'U635' as code union 
  select 'U526' as code union 
  select '28FX' as code
  ) as t 
 left outer join mytable on t.code = mytable.key_field
 group by t.code
 order by t.code;

答案 1 :(得分:1)

该查询只会因为它们不存在而失败,因为它不存在,因为它们不存在。

所以,这样做:

create table #temptable(
  key_field varchar(4)
)

insert into #temptable values ("UXT8"), ("U61J"), ("U61W"), ("U62U"), ("X82U"), ("U5NF"), ("U635"), ("U526"), ("28FX")

和后记做这个选择:

select a.key_field, case when b.counter is null then 0 else b.counter end as counter from #temptable a
left outer join
(select key_field, count(*) counter from table
where key_field in ("UXT8","U61J","U61W","U62U","X82U","U5NF","U635","U526","28FX")
group by key_field) b on a.key_field = b.keyfield

答案 2 :(得分:0)

不,你不能在SQL中做到这一点,除了在支持派生表的方言中,使用一种非常丑陋的方法,涉及n选择“select'utx8'形式的联合。一个更可行的替代方案是将这些值插入到临时表中,并将外部联接插入到该表中。

答案 3 :(得分:0)

只需使用not in找出与给定列表中的任何值都不匹配的key_fields。

select key_field, count(*) as counter
  from table
 where key_field in ('UXT8','U61J','U61W','U62U','X82U','U5NF','U635','U526','28FX')
 group by key_field

 union all

select key_field, 0 as counter
  from table
 where key_field not in ('UXT8','U61J','U61W','U62U','X82U','U5NF','U635','U526','28FX')
 group by key_field;

您只需要使用第二个查询创建一个union,该查询看起来像第一个但not in运算符和零计数器。

答案 4 :(得分:0)

SELECT key_field, COALESCE(cnt, 0) as cnt
FROM (
  SELECT 'UXT8' AS key_field UNION ALL
  SELECT 'U61J' AS key_field UNION ALL
  SELECT 'U61W' AS key_field UNION ALL
  SELECT 'U62U' AS key_field UNION ALL
  SELECT 'X82U' AS key_field UNION ALL
  SELECT 'U5NF' AS key_field UNION ALL
  SELECT 'U635' AS key_field UNION ALL
  SELECT 'U526' AS key_field UNION ALL
  SELECT '28FX'    
) as f
LEFT JOIN (
  SELECT key_field, count(*) as cnt
  FROM thetable
  WHERE key_field IN ("UXT8","U61J","U61W",
                      "U62U","X82U","U5NF",
                      "U635","U526","28FX")
  GROUP BY key_field) as cnts
USING (key_field);