[英]When selecting a record from a joined table get the most recent record from the B (joined) table for each A table record if possible
我有一个历史记录表,并加入了一个评论表。 两者都有日期 - 因此会创建历史记录,并且有一个评论表记录对该历史记录的评论。
当我查询这些表格时,我想要所有的历史记录,以及每个表格的最新评论。 不幸的是,我似乎没有按照我的意愿取回数据,因为如果将评论添加到较早的历史记录中,那么此查询将返回最近的历史记录(正确)但总体上是最近的评论(不正确)而不是我正在查看的历史记录的最新评论。
这是我们的 MySQL
SELECT h.id
, c.id comment_id
, c.comment recent_comment
, h.*
FROM crm_device_history h
LEFT
JOIN crm_device_history_comments c
ON c.crm_device_history_id = h.id
AND c.id = ( SELECT max(id)
FROM crm_device_history_comments
WHERE c.crm_device_history_id = h.id )
WHERE device_id = 147
AND crm_history_states_id >= 0
ORDER
BY h.id DESC
crm_device_history 表
id
device_id
crm_history_states_id
userID
dateTime
system_comment
comment -> this field is to be dropped now we have a separate table
distributor_assignment
client_assignment
updated_date
created_date
crm_device_history_comments
id
crm_device_history_id
comment
user_id
updated_date
试试这个
SELECT
h.id,
sub_query.id AS comment_id,
c.comment as recent_comment,
h.*
FROM
crm_device_history h
INNER JOIN
(SELECT
max(id) as id,
crm_device_history_id
FROM
crm_device_history_comments
GROUP BY
crm_device_history_id)
AS sub_query ON sub_query.crm_device_history_id = h.id
INNER JOIN
crm_device_history_comments AS c ON c.id = sub_query.id
WHERE device_id = 147 AND h.crm_history_states_id >= 0
ORDER BY h.id DESC
尝试这个
SELECT h.id,
c.id AS comment_id,
c.comment AS recent_comment,
h.*
FROM crm_device_history h
LEFT JOIN (SELECT Max([date]),
id
FROM crm_device_history_comments
GROUP BY id) c
ON c.crm_device_history_id = h.id
WHERE device_id = 147
AND crm_history_states_id >= 0
ORDER BY h.id DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.