table 1
:id1, name, surname
table 2
:id1, id2, value
id1
是foreign key
table 2
查找表2中没有value = c
的记录的表1记录的最快查询是什么?
你能帮帮我吗?
答案 0 :(得分:1)
一般情况下,查询注定要慢。
select * from table1 where not exists
( select id1 from table2 where table1.id1 = table2.id2 and value = с )
答案 1 :(得分:0)
您可以使用NOT IN
或NOT EXISTS
。以下是比较website的功能。
答案 2 :(得分:0)
select * from table1 as tb1
where tb1.id1 not in
(select tb2.id1 from table2 as tb2
where tb1.id1 = tb2.id1
and value='c')
当然在很大程度上取决于table1和table2的大小,但我发现内部查询比我最初通过测试假设的效率要高得多。
答案 3 :(得分:0)
此查询将为您提供表1中
的所有记录SQL:
SELECT *
FROM table1
WHERE id1 NOT IN
(SELECT id1 FROM table2 WHERE value = 'c')
此查询将为您提供表1中
的所有记录SQL:
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t1.id1 = t2.id1
WHERE t1.id1 NOT IN
(SELECT id1 FROM table2 WHERE value = 'c')
答案 4 :(得分:0)
你可以尝试这个解决方案,
WITH MISSING (id1)
AS
(
SELECT id1 FROM table1
EXCEPT
SELECT distinct id1 FROM table2 WHERE value = 'c'
)
SELECT * FROM table1 t inner join MISSING m on t.id1 = m.id1;
-- or
SELECT * FROM table1 t WHERE EXISTS (SELECT id1 FROM MISSING m WHERE t.id1 = m.id1);
答案 5 :(得分:0)
SELECT *
FROM table1
WHERE id1 NOT IN
(SELECT id1 FROM table2 WHERE value = 'c')