选择union all cursor

时间:2013-05-30 13:20:16

标签: mysql loops cursor

我有以下表格

tab_1: 

(rs)
rs1
rs2
rs3

tab_2: 

(rs) (cell) (tf)
rs1  A549    tf1
rs1  C555    tf2
rs3  B333    tf1

我需要在tab_1 only列上循环并检查:

SELECT count(distinct cell) from tab_2 where rs = 'rs1'
union all
SELECT count(distinct cell) from tab_2 where rs = 'rs2'
union all
SELECT count(distinct cell) from tab_2 where rs = 'rs3';

并获得结果

2
0
1

无法理解Cursor应该如何工作或只是一个简单的循环(

1 个答案:

答案 0 :(得分:2)

如果您要包含rs2但不是tab_1的{​​{1}}的零点数,则需要tab_2

此外,每个值都不需要LEFT JOIN - 基本UNION可以解决问题:

GROUP BY

使用您的示例数据,此查询的结果为:

SELECT tab_1.rs, COUNT(DISTINCT tab_2.cell)
FROM tab_1
LEFT JOIN tab_2 ON tab_1.rs = tab_2.rs
GROUP BY tab_1.rs
ORDER BY tab_1.rs

有一个SQLFiddle here