我有以下sql
查询。我只想为给定的max(v.id)
选择v.id
而不是全部p_id
。
你能帮帮我吗?
SELECT
v.id,
u.firstname as author_name,
u.lastname as author_surname,
FROM ps_versioning as v
INNER JOIN u_users as u ON u.user_id = v.user_id
where v.patient_id = p_id
除了公认的解决方案,我发现了另一种使用order by v.id desc Limit 1
实现它的方法。请参阅下面的完整示例:
SELECT
v.id,
u.firstname as author_name,
u.lastname as author_surname,
FROM ps_versioning as v
INNER JOIN u_users as u ON u.user_id = v.user_id
where v.patient_id = p_id
order by v.id desc Limit 1
答案 0 :(得分:1)
这将完成这项工作:
SELECT
v.id,
u.firstname as author_name,
u.lastname as author_surname,
FROM ps_versioning as v
INNER JOIN u_users as u ON u.user_id = v.user_id
where v.patient_id = p_id
AND v.id = (SELECT MAX(id) FROM ps_versioning GROUP BY patient_id)
答案 1 :(得分:1)
连接子查询,假设使用u_users表来过滤ps_versioning表行: -
SELECT
v.id,
u.firstname as author_name,
u.lastname as author_surname
FROM ps_versioning v
INNER JOIN u_users u ON u.user_id = v.user_id
INNER JOIN
(
SELECT v.patient_id, MAX(v.id) AS max_id
FROM ps_versioning v
INNER JOIN u_users u ON u.user_id = v.user_id
WHERE v.patient_id = p_id
GROUP BY v.patient_id
) sub0
ON v.id = sub0.max_id
如果ps_versioning上没有行在users表上没有匹配的行,那么您可以省去子查询中的额外内部联接。
SELECT
v.id,
u.firstname as author_name,
u.lastname as author_surname
FROM ps_versioning v
INNER JOIN u_users u ON u.user_id = v.user_id
INNER JOIN
(
SELECT v.patient_id, MAX(v.id) AS max_id
FROM ps_versioning v
WHERE v.patient_id = p_id
GROUP BY v.patient_id
) sub0
ON v.id = sub0.max_id