如何将这两个查询合并为一个?首先,我从id
doorbots
select id --> 2576673
from doorbots
where device_id = '38d269cf5d1f';
然后我使用此id
从id
表中选择dings
select id
from dings
where doorbot_id = 2576673 and deleted_at is NULL;
如何将这两个查询合并为一个?
答案 0 :(得分:1)
使用in
语句,您可以询问您想要的特定ID。
试试这个: -
select id
from dings
where doorbot_id in (select id
from doorbots
where device_id = '38d269cf5d1f')and deleted_at is NULL;
答案 1 :(得分:1)
如果两个表都具有
之类的关系,则可以使用左连接或连接来组合它SELECT d.id
FROM dings d
LEFT JOIN doorbots ON dbs dbs.id = d.doorbot_id
WHERE d.deleted_at IS NULL AND dbs.device_id = '38d269cf5d1f';
SELECT d.id
FROM dings d
JOIN doorbots ON dbs dbs.id = d.doorbot_id
WHERE d.deleted_at IS NULL AND dbs.device_id = '38d269cf5d1f';
或者像这样
SELECT id
FROM dings
WHERE id IN (
SELECT id
FROM doorbots
WHERE device_id = '38d269cf5d1f'
) AND d.deleted_at IS NULL;
答案 2 :(得分:0)
你只需要更换" 2576673"在您的第一个查询的第二个查询中,括号括起来。
答案 3 :(得分:0)
您可以通过树方式获得相同的结果,但仍然使用 IN,EXISTS 和 JOIN 进行单个查询。
使用:
SELECT id
FROM dings
WHERE doorbot_id IN
(SELECT id
FROM doorbots
WHERE device_id = '38d269cf5d1f')
AND deleted_at IS NULL;
使用EXISTS:
SELECT id
FROM dings
WHERE doorbot_id EXISTS
(SELECT 1
FROM doorbots
WHERE dings.doorbot_id =id and device_id = '38d269cf5d1f')
AND deleted_at IS NULL;
使用加入:
SELECT dings.id
FROM doorbots
JOIN dings
ON doorbots.id = dings.doorbot_id
WHERE doorbots.device_id = '38d269cf5d1f'
AND dings.deleted_at IS NULL;
答案 4 :(得分:0)
您可以通过多种方式实现相同目标。使用JOIN
,EXISTS
或IN
。 EXISTS
和IN
都使用子查询。所以我建议你去JOIN
。你可以这样做:
SELECT d.id
FROM dings d
INNER JOIN doorbots db ON d.doorbot_id=db.id
WHERE db.device_id='38d269cf5d1f' AND d.deleted_at IS NULL