我有一个类似于以下的查询,并且想知道DB2抱怨ORDER BY子句中的关联使用。它错误的像是
[42703] [ - 206]“A.ID”在使用它的上下文中无效。 SQLCODE = -206,SQLSTATE = 42703
我能够重写查询以避免相关用法,但我无法在文档中找到关于此的参考。这是一个错误还是我无法找到预期行为的详细信息?
SELECT a.id
FROM A a
ORDER BY (
SELECT COUNT(*)
FROM B b
WHERE b.id = a.id
)
答案 0 :(得分:0)
您不能在order by子句中使用相关查询。但是,有很多方法可以获得相同的结果,例如
select count(*) as count_num ,a.ID
from
a join b on a.ID=b.ID
GROUP BY a.ID
order by 1 DESC
答案 1 :(得分:0)
解决方案1:
SELECT a.id, (select count(*) from B where B.id=a.id) nbOFB
FROM A
order by 2
答案 2 :(得分:0)
解决方案2:
select * from (
SELECT a.id, (select count(*) from B where B.id=a.id) nbOFB
FROM A
) tmp
order by nbOFB
答案 3 :(得分:0)
解决方案3:
SELECT a.id, c.nb
FROM A
inner join lateral
(
select count(*) nb from B where B.id=a.id
) c on 1=1
order by c.nb
答案 4 :(得分:0)
解决方案4:
SELECT a.id, ifnull(c.nb, 0) nb
FROM A
left outer join
(
select b.id, count(*) nb from B group by b.id
) c on a.id=c.id
order by ifnull(c.nb, 0)
答案 5 :(得分:0)
解决方案5:
with c as (
select b.id, count(*) nb from B group by b.id
)
SELECT a.id, ifnull(c.nb, 0) nb
FROM A left outer join c on a.id=c.id
order by ifnull(c.nb, 0)