我想在mysql中创建一个视图。但是在mysql中它不支持子查询。 如何编写没有子查询的sql?
select * from dev_location t1
inner join
(
select
`dev_location`.`device_id` AS `device_id`,
max(`dev_location`.`id`) AS `id`
from
`dev_location`
group by `dev_location`.`device_id`) t2
on t1.id = t2.id
答案 0 :(得分:0)
MySQL视图不支持from
子句中的子查询。以下内容应在视图中起作用:
select dl.*
from dev_location dl
where not exists (select 1
from dev_location dl2
where dl2.device_id = dl.device_id and
dl2.id > dl.id
);
这会重新调整查询说:"从dev_location
device_id
没有更大id
的{{1}}获取所有行。"这是获得最大值的尴尬方式。
并且,如果索引位于dev_location(device_id, id)
,则其效果可能会比您的版本更好。