我必须构建以下查询,但在select max()部分中没有想法。
有这两个表:
玩家
-------------
| id | name |
-------------
| 1 | AAAA |
-------------
| 2 | BBBB |
-------------
分数
----------------------------------------
| player_id | score | created |
----------------------------------------
| 1 | 1080 | 2015/12/28 15:38 |
----------------------------------------
| 1 | 1199 | 2015/12/28 16:00 |
---------------------------------------|
| 2 | 2400 | 2015/12/29 10:30 |
----------------------------------------
| 2 | 2420 | 2015/12/29 10:41 |
----------------------------------------
| 2 | 2031 | 2015/12/29 11:12 |
----------------------------------------
结果我想:
----------------------------
| id | name | latest_score |
----------------------------
| 1 | AAAA | 1199 |
----------------------------
| 2 | BBBB | 2031 |
----------------------------
SQL查询#1 - 此查询提供了我想要的上述结果
SELECT
players.id AS id,
players.name AS name,
scores.player_id,
scores.score AS latest_score,
scores.created
FROM
players
JOIN scores ON
players.id = scores.player_id
WHERE
scores.created IN(
SELECT MAX(scores.created)
FROM
scores
WHERE
scores.player_id= player.id
)
SQL查询#2 - @ tim-biegeleisen,也可以,或者你可以帮我构建这个查询?
SELECT p.id, p.name, s1.score AS latest_score
FROM players p INNER JOIN scores s1
ON p.id = s1.player_id
INNER JOIN
(
SELECT s.player_id, MAX(s.created) AS latest
FROM scores s
GROUP BY s.player_id
) s2
ON s1.player_id = s2.player_id AND s1.created = s2.latest
目前正在尝试构建类似的内容:
$query = $this->Players->find()
->select([
"Players.id",
"Players.name",
"Scores.scores",
"Scores.created"
])
->join([
"Scores" => [
"table" => "scores",
"type" => "left",
"conditions" => "Players.id = Scores.player_id"
]
])
->where([
"Scores.created" =>
$this->Players->Scores->find()
->select(["MAX(Scores.created)"])
->where(["Scores.player_id = Players.id"])
]);
问题是,此构建器不起作用:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MariaDB服务器版本相对应的手册,以便使用接近&#; MAX的正确语法(`Scores__created`)FROM得分分数WHERE Scores.player_id = Players.i'在第1行
我不想只是建立一个联接然后订购Scores.created
desc,并抓住[0]
来获得第一行。您知道如何构建此查询吗?请帮忙。
谢谢!
答案 0 :(得分:2)
尝试使用CakePHP SQL函数语法:
$subquery = $this->Players->Scores->find();
$query = $this->Players->find()
->select([
"Players.id",
"Players.name",
"Scores.scores",
"Scores.created"
])
->join([
"Scores" => [
"table" => "scores",
"type" => "left",
"conditions" => "Players.id = Scores.player_id"
]
])
->where([
"Scores.created" => $subquery
->select([$subquery->func()->max('Scores.created')])
->where(["Scores.player_id = Players.id"])
]);
您可以阅读有关CakePHP 3 here.
的ORM SQL函数的文档答案 1 :(得分:1)
我不是CakePHP专家,但我可以为您提供以下连接查询,以避免WHERE
子句中的子查询。也许这可以帮助您找到解决问题的方法。
SELECT p.id, p.name, s1.score AS latest_score
FROM players p INNER JOIN scores s1
ON p.id = s1.player_id
INNER JOIN
(
SELECT s.player_id, MAX(s.created) AS latest
FROM scores s
GROUP BY s.player_id
) s2
ON s1.player_id s2.player_id AND s1.created = s2.latest