I want to select all information, for today, as a variable like so:
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` = 开发者_Python百科'BD' and `date` LIKE '03/28%'
But instead of doing a new query for each, I just want to come up with:
$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;
How would I go about doing this?
Use:
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%'
You could try something like this
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`
however this will not return zeroes for non-existant cat
values
Just change the start of each query from
SELECT * FROM ...
to
SELECT COUNT(*) FROM ...
I think an array of those search terms along with either variable variables or arrays indexed in that fashion would be easiest way to get this done. Greatly simplifies adding or removing new terms also.
$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
Single Query
$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
精彩评论