【问题标题】:Counting number of non-referenced rows in a table计算表中未引用的行数
【发布时间】:2020-08-29 11:30:14
【问题描述】:

我有一个表addresses 和许多表都有一个引用地址的address_id 列(都有外键约束)。我想找出没有从任何其他表中引用的地址数。

我尝试了以下查询,但速度很慢:

SELECT COUNT(*)
FROM addresses A
LEFT JOIN customers C ON C.address_id = A.id
LEFT JOIN agreements AG ON AG.address_id = A.id
LEFT JOIN products P ON P.address_id = A.id
LEFT JOIN letters L ON L.address_id = A.id
WHERE C.id IS NULL
AND AG.id IS NULL
AND P.id IS NULL
AND L.id IS NULL

有什么方法可以做到这一点,而无需永远查询?

【问题讨论】:

标签: mysql count subquery left-join query-performance


【解决方案1】:

我会先用not exists重写这个:

select count(*)
from addresses a
where 
        not exists (select 1 from customers c  where c.address_id = a.id)
    and not exists (select 1 from agreements g where g.address_id = a.id)
    and not exists (select 1 from products p   where p.address_id = a.id)
    and not exists (select 1 from letters l    where l.address_id = a.id)

然后,确保有以下索引以加快查询速度:

customers(address_id)
agreements(address_id)
products(address_id)
letters(address_id)

如果您已将address_id 列正确定义为address(id) 的外键,那么这些索引已经存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2016-06-09
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2010-11-12
    • 2015-05-09
    • 1970-01-01
    相关资源
    最近更新 更多