Php 如何仅选择最新添加的记录以避免重复
我需要从表Php 如何仅选择最新添加的记录以避免重复,php,mysql,sql,Php,Mysql,Sql,我需要从表competition\u rounds中选择链接到competition\u seasures表的seasures\u id列的最新添加记录,例如: 比赛\u轮 id | name | season_id 1 Round A 20 2 Round B 20 3 Round A 21 4 Round B 21 竞争季节 id | name | competition_id
competition\u rounds
中选择链接到competition\u seasures
表的seasures\u id
列的最新添加记录,例如:
比赛\u轮
id | name | season_id
1 Round A 20
2 Round B 20
3 Round A 21
4 Round B 21
竞争季节
id | name | competition_id
20 2017/2018 40
21 2018/2019 40
我只想退货:
round_id | round_name | season_id | season_name
3 Round A 21 2018/2019
4 Round B 21 2018/2019
问题在于,我的查询返回所有可用回合:
$sql = $this->db->prepare("SELECT max(r.id) AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r
JOIN competition_seasons s ON r.season_id = s.id
JOIN competition c ON s.competition_id = c.id
WHERE c.id = :competition_id
GROUP BY r.id
ORDER BY max(r.season_id) DESC");
$sql->bindParam("competition_id", 40);
$sql->execute();
$rounds = $sql->fetchAll();
return $response->withJson($rounds);
注意:表
competition
仅包含一个竞赛参考列表。您在SELECT
中没有任何competition
列,因此您可以从查询中省略它。
就给定的:竞赛\u id
SELECT r.id AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r
JOIN competition_seasons s ON r.season_id = s.id
WHERE s.id = (SELECT max(cs.id)
FROM competition_seasons cs
WHERE cs.competition_id = :competition_id)
如果我理解正确,您可以使用子查询从seasons表中仅返回最新的季节:
SELECT r.id AS round_id,
r.name as round_name, r.season_id AS season_id, s.name AS season_name
FROM competition_rounds r JOIN
(SELECT s.*
FROM competition_seasons s
WHERE s.competition_id = :competition_id
ORDER BY s.id DESC
LIMIT 1
) s
ON r.season_id = s.id ;
您的问题只提到两个表,尽管查询有三个表。这只是基于这个问题