MYSQL:从多个表返回多个计数而无需加入

时间:2018-12-28 16:20:04

标签: mysql

declare -a arr=( $( for f in $SOURCE_DIR/*.json do d=${f%/*} # get dir path f=${f##*/} # strip path g=${f:0:2} # get leading str ( cd $d && printf "%s\n" ${g}*.json | sort -n | sed -n '$ { s/[.].*//; p; }' ) done | sort -u ) ) echo "[ ${arr[@]} ]" [ a_v5 c_v1 f_v40 ] 表具有accountsaccount_idaccount_type

date_opened表具有loansaccount_id

选择新贷款的数量:

balance

选择未偿还贷款的数量:

select count(a.account_id) from account a
    where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH)
    and a.account_type = 'L'

select count(*) from loans l 
    where l.balance > 0

如何一次选择呢?我尝试过的事情:

SUM(CASE WHEN l.balance > 0 THEN 1 ELSE 0 END) as loans_opened

归还0笔贷款

select 
    count(a.account_id),
    SUM(CASE WHEN l.balance > 0 THEN 1 ELSE 0 END) as loans_opened
    from account a as new_loans,
    LEFT JOIN loans l ON l.account_id = a.account_id
    where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH) and a.account_type = 'L'

查询永不返回

有没有连接的方法?

2 个答案:

答案 0 :(得分:1)

您可以通过使用两个SELECT查询作为主查询的SELECT列表中的子查询来完成此操作:

SELECT (SELECT COUNT(*)
        FROM account
        WHERE date_opened > LAST_DAY(NOW() - INTERVAL 1 MONTH)
        AND account_type = 'L') AS new_loans,
       (SELECT COUNT(*)
        FROM loans
        WHERE balance > 0) AS open_loans;

答案 1 :(得分:0)

您尝试过这样的事情吗?

select (select count(*) from loans l where l.balance > 0) loans_opened,(select count(a.account_id) from account a where a.date_opened > LAST_DAY(now() - INTERVAL 1 MONTH) and a.account_type = 'L') new_loans;