我不知道如何实现这一点。
我的数据库中有2个表:
表1:轮次
+------------+----------+---------+----------+---------------+
| round_id | format | Size | poster | tournament_id |
+------------+----------+---------+----------+---------------+
| 6 | Single | 12 | Luis | 1
| 7 | Single | 9 | Daniel | 1 |
| 8 | Single | 4 | Oscar | 1 |
+------------+----------+---------+----------+---------------+
表2:匹配
+------------+----------+-------------+----------+----------+
| round_id | player | position | score | winner |
+------------+----------+-------------+----------+----------+
| 6 | Doris | 0 | 1 | 1 |
| 7 | Arturo | 0 | 3 | 1 |
| 7 | Pablo | 1 | 2 | 0 |
| 8 | Ale | 0 | 1 | 0 |
| 8 | Maria | 1 | 5 | 1 |
| 8 | Roberto | 2 | 4 | 0 |
+------------+----------+-------------+----------+----------+
在第一桌我有几轮比赛,在第二桌有每轮比赛,因为你可以看到一轮中的每场比赛有不同规模的球员。所以我想获得轮次的所有信息 BUT 只是表格中的最后两轮"轮次",在一个查询中得到类似的内容:
查询结果:
//主键可以是round_id或0到n的数字 //
[7] => Array
(
['poster'] => 'Daniel'
['format'] => 'single'
(
[0] => Array
(
['player'] => 'Arturo'
['score'] => 3
)
[1] => Array
(
['player'] => 'Pablo'
['score'] => 2
)
)
)
[8] => Array
(
['poster'] => 'Oscar'
['format'] => 'single'
(
[0] => Array
(
['player'] => 'Ale'
['score'] => 1
)
[1] => Array
(
['player'] => 'Maria'
['score'] => 5
)
[2] => Array
(
['player'] => 'Roberto'
['score'] => 4
)
)
)
因此,在我的页面中,我可以显示上传的最后一轮,如下所示:
+---------------------------+
| by Daniel |
| Arturo (3) vs Pablo (2) |
+---------------------------+
+---------------------------------------+
| by Oscar |
| Ale (1) vs Maria (5) vs Roberto (4) |
+---------------------------------------+
希望MySQL专家可以帮助我:)
答案 0 :(得分:1)
使用子查询加入matches
表,该子查询获取rounds
表中的最后两行。
SELECT *
FROM (SELECT *
FROM rounds
ORDER BY round_id DESC
LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id
请参阅Creating one array from another array in php,了解如何组合PHP数组中同一轮的匹配信息。
如果您希望查询每轮返回一行,您可以使用GROUP_CONCAT
将match
信息合并到一个列中:
SELECT r.poster, r.format, GROUP_CONCAT(CONCAT(m.player, '(', m.score, ')') SEPARATOR ' vs ') AS players
FROM (SELECT round_id, poster, format
FROM rounds
ORDER BY round_id DESC
LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id
GROUP BY m.round_id