MariaDB / Mysql左连接未按预期工作

时间:2017-09-18 10:36:26

标签: mysql left-join

select count(*) from devices - >返回编号241

select count(*) from address_devices - >返回编号200

select d.DeviceID,adl.DeviceID
from devices d
left join (
    select ad.* from address_devices ad
    where ad.id in (
            SELECT max(sad.id) as max_id
            from address_devices sad 
            group by sad.DeviceID
    ) 
) as adl
on d.DeviceID = adl.DeviceID

我希望SQL查询返回241行但它只返回137.

有什么我想念的吗?我会假设,即使adl.DeviceIDnull,它仍然会在设备表左侧显示记录

1 个答案:

答案 0 :(得分:0)

select d.DeviceID,adl.DeviceID,
(select * from address_devices ad
    where ad.id in (
            SELECT max(sad.id) as max_id
            from address_devices sad 
            group by sad.DeviceID
    ) 
) as adl from devices d left join address_devices ad1
on d.DeviceID = adl.DeviceID