4

我有两个具有以下设置的表:

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)

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

4

2 回答 2

5

转换IN (SELECT)toEXISTS (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
于 2012-08-12T22:59:39.547 回答
0

使用加入:

SELECT c.id, c.name
FROM   category c
JOIN item i on c.id=i.category_id 
GROUP BY c.id, c.name
于 2012-08-12T22:58:32.480 回答