如果表数据库是这样的
设备表
device_id device_uuid device_status
1001 00000脱机
1002 00000在线
1003 11111脱机
1004 11111脱机
任务表
task_id device_id task_value
50001 1001清洗
50002 1001清洗
50003 1004清洗
我的sql
select t.*
from task t
where t.device_id in (select device_id
from device d1
where d1.device_uuid in (select device_uuid
from device d
where d.device_status = 'online'
)
)如何优化?谢谢!
发布于 2022-04-25 10:23:48
您可以使用JOIN或EXISTS:
select t.*
from task t
where exists (select 1
from device d1
where d1.device_id = t.device_id and
d1.device_status = 'online'
); 发布于 2022-04-25 17:34:18
使用JOINs。模仿你的想法--“先找到‘在线’设备,然后.”:
SELECT t.*
FROM device d
JOIN device d1 USING(device_uuid)
JOIN task t USING(device_id)
WHERE d.device_status = 'online';我不清楚是否需要两次接触device。也许这就足够了:
SELECT t.*
FROM device d
JOIN task t USING(device_id)
WHERE d.device_status = 'online';注:
FROM a JOIN b USING(x)是一个缩写
FROM a JOIN b ON b.x = a.x还有一个问题--指数。一定要有这些;如果表很大,它们将有很大的帮助:
device: INDEX(device_status, device_id)
task: INDEX(device_id)另一个注意事项:关键字INNER和OUTER在MySQL中没有功能,因此我忽略了它们。
https://stackoverflow.com/questions/71997924
复制相似问题