【问题标题】:mySQL query, data as a php variable?mySQL 查询,数据作为 php 变量?
【发布时间】:2011-07-24 04:19:55
【问题描述】:
我想选择今天的所有信息,作为这样的变量:
SELECT * FROM `table` WHERE `cat` = 'BA' and `date` LIKE '03/28%'
SELECT * FROM `table` WHERE `cat` = 'BB' and `date` LIKE '03/28%'
SELECT * FROM `table` WHERE `cat` = 'BC' and `date` LIKE '03/28%'
SELECT * FROM `table` WHERE `cat` = 'BD' and `date` LIKE '03/28%'
但我不想为每一个都做一个新的查询,我只想想出:
$ba = the total number of results returned;
$bb = the total number of results returned;
$bc = the total number of results returned;
$bd = the total number of results returned;
我该怎么做呢?
【问题讨论】:
标签:
php
mysql
sql
aggregate-functions
【解决方案1】:
你可以试试这样的
SELECT `cat`, COUNT(1) AS total
FROM `table`
WHERE `date` LIKE '03/28%'
AND `cat` IN ('BA', 'BB', 'BC', 'BD') -- optional if these are the only `cat` values
GROUP BY `cat`
ORDER BY `cat`
但是,这不会为不存在的 cat 值返回零
【解决方案2】:
我认为这些搜索词的数组以及以这种方式索引的变量变量或数组将是完成此任务的最简单方法。也大大简化了添加或删除新术语的过程。
$searches = ['ba', 'bb', 'bd']
foreach($search as $v)
{
$r = mysql_query("SELECT COUNT(*) FROM `table` WHERE `cat` = UCASE('$v') and `date` LIKE '03/28%'");
$arr = mysql_fetch_assoc($r);
$$v = $r['count'];
}
echo $ba; //to test
单个查询
$searches = ['ba', 'bb', 'bd']
$sql = "SELECT ";
foreach($search as $v)
{
$sql .= "SUM(CASE WHEN t.cat = UCASE('$v') THEN 1 ELSE 0 END) AS $v, ";
}
$sql .= "FROM table T WHERE t.date LIKE '03/28%'";
$r = mysql_query($sql);
$arr = mysql_fetch_assoc($r);
echo $arr['ba']; //test
【解决方案3】:
用途:
SELECT SUM(CASE WHEN t.cat = 'BA' THEN 1 ELSE 0 END) AS ba,
SUM(CASE WHEN t.cat = 'BB' THEN 1 ELSE 0 END) AS bb,
SUM(CASE WHEN t.cat = 'BC' THEN 1 ELSE 0 END) AS bc,
SUM(CASE WHEN t.cat = 'BD' THEN 1 ELSE 0 END) AS bd
FROM YOUR_TABLE t
WHERE t.date LIKE '03/28%'
【解决方案4】:
只需更改每个查询的开头
SELECT * FROM ...
到
SELECT COUNT(*) FROM ...