如何使这个查询简单而简短。 (my_sql)和PHP

时间:2018-04-05 06:39:38

标签: php mysql sql variables phpmyadmin

我提供了两个包含两种类型查询的php,有人可以帮我把这个查询缩短。提前致谢

<?php $sel = mysql_query("SELECT COUNT( form ) AS ML FROM webcm WHERE department ='PDN-ML' AND DATE = CURDATE()");
$get_sel = mysql_fetch_array($sel); 
$PDNML1 = $get_sel['ML'];

$sel1 = mysql_query("SELECT COUNT( form ) AS HM FROM webcm WHERE department ='PDN-HM' AND DATE = CURDATE()");
$get_sel1 = mysql_fetch_array($sel1); 
$PDNHM1 = $get_sel1['HM'];

$sel2 = mysql_query("SELECT COUNT( form ) AS AI FROM webcm WHERE department ='AI' AND DATE = CURDATE()");
$get_sel2 = mysql_fetch_array($sel2); 
$AI1 = $get_sel2['AI'];

$sel3 = mysql_query("SELECT COUNT( form ) AS SMT FROM webcm WHERE department ='SMT' AND DATE = CURDATE()");
$get_sel3 = mysql_fetch_array($sel3); 
$SMT1 = $get_sel3['SMT'];?>

4 个答案:

答案 0 :(得分:1)

SELECT SUM(`ML`) AS `ML`,
       SUM(`HM`) AS `HM`,
       SUM(`AI`) AS `AI`,
       SUM(`SMT`) AS `SMT`
FROM (
SELECT SUM( CASE WHEN department='PDN-ML' THEN 1 ELSE 0 END) AS `ML`,
       SUM( CASE WHEN department='PDN-HM' THEN 1 ELSE 0 END) AS `HM`,
       SUM( CASE WHEN department='AI' THEN 1 ELSE 0 END) AS `AI`,
       SUM( CASE WHEN department='SMT' THEN 1 ELSE 0 END) AS `SMT`
FROM webcm 
WHERE DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT') 
AND DATE = CURDATE()
) AS T

<强>样本

  

http://sqlfiddle.com/#!9/9e8fcf/1

答案 1 :(得分:0)

也许你能做的是:

SELECT COUNT( form ) AS ML, department  
FROM webcm WHERE DATE = CURDATE() 
AND DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT') 
group by department

您可以访问所有内容,$get_sel2['ML']会给您统计,$get_sel2['department']会为您提供部门名称或代码。

然后你将有一个计数和相应部门的查询结果。

答案 2 :(得分:0)

试试这个

<?php $sel = mysql_query("SELECT count(*) as ML,department from webcm where DATE = CURDATE() GROUP BY department  ");
$get_sel = mysql_fetch_array($sel); 
$PDNML1 = $get_sel['ML'];

OR

<?php $sel = mysql_query("SELECT count(*) as ML,department from webcm where DATE = CURDATE() and DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT') GROUP BY department  ");
$get_sel = mysql_fetch_array($sel); 
$PDNML1 = $get_sel['ML'];

答案 3 :(得分:0)

SELECT department,
   case when department='PDN-ML' then COUNT( form ) else 0 end AS ML , 
   case when department='PDN-HM' then COUNT( form ) else 0 end AS HM,
   case when department='AI' then COUNT( form ) else 0 end AS AI,
   case when department='SMT' then COUNT( form ) else 0 end AS SMT,
FROM webcm 
WHERE DEPARTMENT IN ('PDN-ML','PDN-HM', 'AI', 'SMT') 
AND DATE = CURDATE()
GROUP BY department