我有两个非常类似的MySQL查询但是它们在特定的COUNT()
子句(WHERE
)上返回type
,所以我想知道它们是否可以合并为1个查询看到只有WHERE
子句(type
)区分两者?
查询1:
SELECT COUNT(referral_id) AS in_count
FROM referrals
WHERE author = '{$author}'
AND type = 'in'
AND ip_address = '{$ip_address}'
LIMIT 1
查询2:
SELECT COUNT(referral_id) AS out_count
FROM referrals
WHERE author = '{$author}'
AND type = 'out'
AND ip_address = '{$ip_address}'
LIMIT 1
非常感谢所有帮助:B
答案 0 :(得分:1)
SELECT SUM(IF(type='in',1,0)) as in_count,
SUM(IF(type='out',1,0)) as out_count
FROM referrals
WHERE author = '{$author}' AND
ip_address = '{$ip_address}'
LIMIT 1
答案 1 :(得分:0)
您只需要一个GROUP BY
条款。
SELECT COUNT(referral_id) AS count, type
FROM referrals
WHERE author = '{$author}'
AND ip_address = '{$ip_address}'
GROUP BY type
LIMIT 1