有没有办法将各种MYSQL查询与多个WHERE子句相结合?

时间:2014-03-13 00:18:00

标签: php mysql sql aggregate-functions

我有以下查询

$queryrs12c = "SELECT COUNT(*) total, SUM(goals) as sumgoals, SUM(assists) as sumassists, SUM(minutes) as summinutes FROM `player` WHERE season='12' AND gametype='club' ";

$queryrs11c = "SELECT COUNT(*) total, SUM(goals) as sumgoals, SUM(assists) as sumassists, SUM(minutes) as summinutes FROM `player` WHERE season='11' AND gametype='club' ";

$queryrs10c = "SELECT COUNT(*) total, SUM(goals) as sumgoals, SUM(assists) as sumassists, SUM(minutes) as summinutes FROM `player` WHERE season='10' AND gametype='club' ";

我有这个查询12次循环通过1-12

然后,我通过循环获取每个查询的结果,以生成12个数据表。

是否可以合并所有12个查询但仍保留生成12个数据表的能力?

(12个查询似乎不多,但我有其他类似的查询,一个有10个查询,一个有12个,一个有13个,有很多变量我需要循环。)

2 个答案:

答案 0 :(得分:1)

SELECT 
    season,
    COUNT(*) total, 
    SUM(goals) as sumgoals, 
    SUM(assists) as sumassists, 
    SUM(minutes) as summinutes 
FROM `player` 
WHERE season between 1 and 12
AND gametype='club'
GROUP BY season

答案 1 :(得分:1)

您应该使用GROUP BY子句,这将允许您对列表中的每个变体使用SUM()等聚合函数。在您的情况下,这可能如下所示:

SELECT
    season,
    COUNT(*) AS total,
    SUM(goals) AS sumgoals,
    SUM(assists) AS sumassists,
    SUM(minutes) AS summinutes
FROM `player`
WHERE gametype='club'
GROUP BY season
ORDER BY season DESC /* or ASC whichever you wish */