转换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