Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

sqlite - Retrieve Record Based on a Value Existing in Record's Association Table

I have two tables. posts is the record I want, whilst post_tags allows a one-to-many relationship between them. NB. I have this working, however, they do not feel efficient to me and I could do with some SQLite gurus to help me out.

posts
id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Usually EXISTS performs better:

SELECT p.* 
FROM posts p 
WHERE EXISTS (SELECT 1 FROM tag t WHERE t.post_id = p.id AND t.tag IN ('tag1', 'tag2'))

Or you could do it with an INNER JOIN:

SELECT DISTINCT p.*
FROM posts p INNER JOIN tag t
ON t.post_id = p.id 
WHERE t.tag IN ('tag1', 'tag2')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...