标题有点绕。这是一个具体的例子。我有两张桌子:
+-------------+--------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------------------------+------+-----+---------+-------+
| event | varchar(100) | NO | MUL | NULL | |
| sport | varchar(100) | NO | | NULL | |
| athleteCode | char(10) | NO | MUL | NULL | |
| medal | enum('GOLD','SILVER','BRONZE') | NO | | NULL | |
+-------------+--------------------------------+------+-----+---------+-------+
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| name | varchar(100) | NO | | NULL | |
| code | char(10) | NO | PRI | NULL | |
| country | varchar(100) | NO | MUL | NULL | |
+---------+--------------+------+-----+---------+-------+
第一桌是奖牌桌。第二张桌子是运动员桌。这两个表通过medals.athleteCode
和关联athlete.code
。我希望能够列出显示以下信息的查询:
COUNTRY | GOLD | SILVER | BRONZE | TOTAL
到目前为止,我能够做到的唯一方法是使用此查询:
SELECT country, medal, COUNT(medal) as count
FROM athletes, medals
WHERE athletes.code=medals.athleteCode
GROUP BY country, medal
ORDER BY country, medal;
但是在我完成这个查询之后,我仍然需要处理这个查询(通过 PHP),因为这只会让我得到每个国家的每种奖牌类型(即所有中国的金牌、所有中国的银牌、所有中国的铜牌等)。有没有办法创建一个查询,其中查询的每条记录(即行)是:COUNTRY | GOLDS | SILVERS | BRONZES | TOTAL
?我看了看,COUNT()
但我不确定如何使用它。
2012.08.17
@"habib zare" 的解决方案非常接近。这是我的调整:
SELECT country,
(SELECT count(*) FROM medals WHERE a.code=m.athleteCode AND medal='Gold') AS Gold,
(SELECT count(*) FROM medals WHERE a.code=m.athleteCode AND medal='Silver') AS Silver,
(SELECT count(*) FROM medals WHERE a.code=m.athleteCode AND medal='Bronze') AS Bronze,
(SELECT count(*) FROM medals WHERE a.code=m.athleteCode) AS Total
FROM medals m JOIN athletes a
ON m.athleteCode=a.code
GROUP BY country
ORDER BY country, Gold DESC, Silver DESC, Bronze DESC
问题是二级SELECT
报表需要根据国家来选择;那就是我需要类似的东西:
SELECT country AS Country,
(SELECT count(*) FROM medals WHERE a.code=m.athleteCode AND medal='Gold' AND a.country=Country) AS Gold,