最佳SQLite查询删除重复项

时间:2012-08-12 20:52:16

标签: sql sqlite

我有两张表,其中包含以下设置:

category: (id, name)
item: (id, name, category_id) - category_id is foreign key to category table

现在我正在编写一个查询来检索仅使用类别的类别表中的子集:

SELECT c.id, c.name
FROM   category c
WHERE  c.id IN (SELECT DISTINCT category_id FROM item)

以上查询工作正常。我只是想知道这是否是进行查询的最佳方式,或者是否可以通过连接或其他方式做其他事情

2 个答案:

答案 0 :(得分:5)

IN (SELECT)转换为EXISTS (SELECT ... WHERE )可能有所帮助:

SELECT c.id, c.name
FROM   category c
WHERE EXISTS (SELECT 1 FROM item WHERE item.category_id = c.id)

另一种可能性(我希望它更慢,但它总是取决于你的数据库):

SELECT c.id, c.name
FROM   category c
INNER JOIN item ON item.category_id = c.id
GROUP BY c.id

或者您可以使用DISTINCT代替GROUP BY

SELECT DISTINCT c.id, c.name
FROM   category c
INNER JOIN item ON item.category_id = c.id

如果速度非常重要,请不要忘记不时致电ANALYZE

http://www.sqlite.org/lang_analyze.html

其他一些有趣的变体:

SELECT c.id, c.name
FROM   category c
INNER JOIN (SELECT DISTINCT item.category_id ) AS i_c ON i_c.category_id = c.id

另:

SELECT c.id, c.name
FROM   category c

EXCEPT

SELECT c.id, c.name
FROM   category c
LEFT JOIN item ON item.category_id = c.id
WHERE item.category_id IS NULL

答案 1 :(得分:0)

使用加入:

SELECT c.id, c.name
FROM   category c
JOIN item i on c.id=i.category_id 
GROUP BY c.id, c.name