通过将两个MySQL查询合并为1来简化它们?

时间:2011-01-09 05:02:14

标签: php mysql

我有两个非常类似的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

2 个答案:

答案 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