如何缩短sql查询

时间:2018-04-17 11:14:41

标签: php mysql sql mysqli

我从表中获得了以下详细信息的总计数

TODAYS Inquiry
TODAYS Leads
TODAYS Quotation
TODAYS Quotation Amount
TODAYS Closed inquiry
TODAYS Payment Amount

因此我使用了以下查询

<?php
  $today1 = "SELECT COUNT(id) AS todayinq FROM `register` WHERE DATE(`ipdatee`) = CURDATE()";
  $today2 = "SELECT COUNT(id) AS todaylead FROM `register` WHERE data_status = 2 AND DATE(`ipdatee`) = CURDATE()";
  $today3 = "SELECT COUNT(id) AS todayqamt FROM `register` WHERE `q_total_amount` > 0 AND DATE(`ipdatee`) = CURDATE()";
  $today4 = "SELECT SUM(q_total_amount) AS todayqamt2 FROM `register` 
             WHERE `q_total_amount` > 0 AND DATE(`ipdatee`) = CURDATE()";
  $today5 = "SELECT SUM(lead_payment_amount) AS todaypamt FROM `register` 
             WHERE `lead_payment_amount` > 0 AND DATE(`ipdatee`) = CURDATE()";
?>

我每周和每月都在做同样的事情所以这段代码重复了X3 Times。所以我的问题是,使用此类型还是有任何方法缩短查询是否有意义?

1 个答案:

答案 0 :(得分:4)

您可以在一个查询中执行此操作:

SELECT COUNT(id) AS todayinq,
       SUM( (data_status = 2) ) as todaylead,
       SUM( (q_total_amount > 0) ) as todayqamt,
       SUM( GREATEST(q_total_amount, 0) ) as totalqamt,
       SUM( GREATEST(lead_payment_amount, 0) ) as todaypamt
FROM register r
WHERE ipdatee >= CURDATE() AND ipdatee < CURDATE() + INTERVAL 1 DAY;

请注意WHERE子句。通过删除DATE()函数,优化程序可以使用ipdatee上的索引(如果存在)。

此查询使用MySQL功能,将布尔值视为数字上下文中的数字,使用&#34; 1&#34;为真和&#34; 0&#34;为假。所以,

SUM( (data_status = 2) )

与:

相同
SUM(CASE WHEN data_status = 2 THEN 1 ELSE 0 END)

通常,我更喜欢标准SQL。这恰好是我真正喜欢的一个特定于数据库的约定,可能是因为C是我学习的第一批语言之一(它遵循相同的约定)。