我正在运行一个分类广告页面,我正在将mysql与php结合使用。 我的ads表作为简化形式如下:
ad id -> int
ad title -> text
ad description -> text
ad description -> text
ad type -> boolean (if 0 is a private add, if is 1 is abusiness ad)
ad op -> boolean if zero is a used item if 1 is a new item)
我想获取私人和公共广告的数量 已使用和新项目的数量,而无需对数据库进行4次调用,
由于我每页显示20个广告,因此我现在打了5个电话 我对数据库的调用是:
是否有某种方法可以执行相同的操作,但对数据库的调用较少?
答案 0 :(得分:2)
您可以将Count()
与If()
结合使用,将最后4个点合并为一个查询:
SELECT
COUNT(IF (`type` = 0, id, NULL)) AS private_ads_count,
COUNT(IF (`type` = 1, id, NULL)) AS business_ads_count,
COUNT(IF (`op` = 0, id, NULL)) AS used_ads_count,
COUNT(IF (`op` = 1, id, NULL)) AS new_ads_count
FROM ads_table
SELECT
SUM(IF (`type` = 0, 1, 0)) AS private_ads_count,
SUM(IF (`type` = 1, 1, 0)) AS business_ads_count,
SUM(IF (`op` = 0, 1, 0)) AS used_ads_count,
SUM(IF (`op` = 1, 1, 0)) AS new_ads_count
FROM ads_table
请注意,type
是Reserved Keyword,因此我们需要在其周围使用反引号(`)。