sql外连接数高于行数

时间:2014-04-27 06:32:30

标签: sql database sqlite join

table 1
_id    sub_id
  1        32
  2        34
  3        42
  4        44
  5        47
  6        50

table 2
_id    sub_id
  1        34
  2        42

我想要结果

_id    sub_id     count
  1        32         2
  2        34         2
  3        42         1
  4        44         0
  5        47         0
  6        50         0

表2子ID 34包含表1,高于32 - >计数+ 1

表2子id 42包含表1,高于32,34,42 - >数+ 1

result 
32, 34 = 2
42 = 1
44, 47, 50 = 0

我尝试外连接,左连接等.... 不正确的结果。

这个正确的结果怎么样?

PLZ。帮我T.T ....

3 个答案:

答案 0 :(得分:2)

尝试此查询

SELECT _id
    ,sub_id
    ,(
        SELECT count(*)
        FROM table2 t2
        WHERE t2.sub_id >= t1.sub_id
        ) count
FROM table1 t1

答案 1 :(得分:1)

这就是你想要的:

SELECT
    t1._id
    ,t1.sub_id
    ,count(t2._id) as count
FROM
    table1 t1
    left join table2 t2
        on t2.sub_id >= t1.sub_id
GROUP BY
    t1._id
    ,t1.sub_id

以下是SQLfiddle demo

答案 2 :(得分:0)

select distinct a.id, a.sub_id, 
case when c.sub_id is  not null then (select count(*) from table2 b 
where a.sub_id<=b.sub_id)
else 0 end  as counter
from table1 a left join table2 c on c.sub_id>=a.sub_id

SQL Fiddle