由于where子句中的select count(1)语句,我有以下SQL查询执行可怕。任何人都可以建议一种可以加快速度的方法吗?我的想法是,我只希望在找到一张发票时返回行。
SELECT people.name, people.address
FROM people
WHERE ((SELECT COUNT(1) FROM invoices WHERE invoices.pid = people.id)=1)
答案 0 :(得分:4)
所以,尝试像这样的JOIN
SELECT people.name, people.address
FROM
people
JOIN
invoices ON invoices.pid = people.id
GROUP BY
people.name, people.address
HAVING
COUNT(*) = 1
我也希望你有索引,至少在invoices.pid和people.pid,姓名,地址
答案 1 :(得分:1)
使用JOIN
:
SELECT people.name, people.address
FROM people
JOIN invoices ON invoices.pid = people.id
GROUP BY people.name, people.address
HAVING Count(*) = 1
答案 2 :(得分:0)
在实践和表现方面,加入表格可能要好得多,我认为。
SELECT people.name, people.address
FROM people INNER JOIN invoices ON invoices.pid = people.id
由于正在编辑OP而进行编辑:您是否只想要那些只拥有一张发票的人?如果是这样,那么忽略这一点,看看其他答案之一。