SELECT子查询where条件的理解 以及 条件域的问题
经常写形如这样的sql:
SELECT l.national_id
,(SELECT COUNT(*) FROM installments WHERE loan_id = l.loan_id) AS total_installments
,l.loan_amount
FROM loans l
我以前知道这会遍历loan的每一条记录,实际上这个就和普通select一个字段是一样的,比如:
SELECT l.national_id
,l.loan_id
,l.loan_amount
FROM loans l
最上面只是用一个表达式包了一下,当然表达式只能返回一行,不能返回多行,否则报错。
另外一点就是域的问题,比如
SELECT l.national_id
,(SELECT SUM(flag) FROM
(SELECT CASE WHEN days > 10 THEN 1 ELSE 0 END AS flag FROM installments WHERE loan_id = l.loan_id) a) AS total_installments
,l.loan_amount
FROM loans l
这种引入了一个子表a,那a中的l,只能在a这个域中查找,显然找不到
SELECT l.national_id
,(SELECT COUNT(*) FROM installments WHERE loan_id = l.loan_id) AS total_installments
,l.loan_amount
FROM loans l
我以前知道这会遍历loan的每一条记录,实际上这个就和普通select一个字段是一样的,比如:
SELECT l.national_id
,l.loan_id
,l.loan_amount
FROM loans l
最上面只是用一个表达式包了一下,当然表达式只能返回一行,不能返回多行,否则报错。
另外一点就是域的问题,比如
SELECT l.national_id
,(SELECT SUM(flag) FROM
(SELECT CASE WHEN days > 10 THEN 1 ELSE 0 END AS flag FROM installments WHERE loan_id = l.loan_id) a) AS total_installments
,l.loan_amount
FROM loans l
这种引入了一个子表a,那a中的l,只能在a这个域中查找,显然找不到
留言
張貼留言