访问mysql数据库并为网站提取多个数据的最有效方法

时间:2018-10-04 10:43:07

标签: php mysql

我正在运行一个分类广告页面,我正在将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个电话 我对数据库的调用是:

  1. 使用select *表获取 20个广告的数据。...LIMIT 1,20
  2. 使用num_rows计算添加的私有数量;
  3. 使用num_rows计算添加的业务数量;
  4. 使用num_rows计算已添加的数量
  5. 使用num_rows计算新添加的数量

是否有某种方法可以执行相同的操作,但对数据库的调用较少?

1 个答案:

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

备用方法是将SUM()函数与IF()结合使用:

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

请注意typeReserved Keyword,因此我们需要在其周围使用反引号(`)。