通过将两个MySQL查询合并为1来简化两个MySQL查询?
问题描述:
我有两个MySQL查询这是非常相似但它们归到一个特定的WHERE
条款(type
)一COUNT()
,所以我想知道他们是否可以合并成1个查询看到,因为只有WHERE
条款(type
)differenciates两个?通过将两个MySQL查询合并为1来简化两个MySQL查询?
查询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
所有帮助是极大的赞赏:乙
答
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
答
你只需要一个GROUP BY
条款。
SELECT COUNT(referral_id) AS count, type
FROM referrals
WHERE author = '{$author}'
AND ip_address = '{$ip_address}'
GROUP BY type
LIMIT 1
+1,只是打字,但打我。对于OP来说,[this MySQL tidbit](http://dev.mysql.com/tech-resources/articles/wizard/page3.html)可能对这类事情有一些帮助。 – 2011-01-09 05:09:42