在编写查询时我犯了一个错误,我编写了一个没有FROM子句的子查询:
select * from foo where id in (select id where type 'mm')
我错了半天才发现一个错误,因为它起作用了!
我检查了文档,但是找不到任何信息……
更有趣:
select * from abc a
inner join abc b on b.id = a.id
where a.id in (select id from (select a.id, row_number () over () lp where b.name = 'abc') x where lp = 1);
http://sqlfiddle.com/#!15/4bb29/12
有人可以解释它的工作原理吗?
答案 0 :(得分:0)
您的第一个查询肯定会不按原样工作。
要了解您的第二个查询,请记住
没有SELECT
子句的FROM
就像是一个FROM
子句,其中的表没有列,只有一行。
您可以在子查询中引用外部查询中的列。
这里尝试解释您的查询:
SELECT * FROM abc a
/* ok, now we have a table with alias "a" */
INNER JOIN abc b ON b.id = a.id
/* now we also have a table with alias "b" */
WHERE a.id IN
(SELECT id
FROM (SELECT a.id,
/* this will count the one "artificial" row */
row_number() OVER () lp
/* Here you reference the table with alias "b" above.
This is constant as far as the subquery is concerned,
so if it is not TRUE, the subquery will return an
empty result */
WHERE b.name = 'abc') x
/* this is always true, since there is only one line in
the above subquery */
WHERE lp = 1);