Having this SQL tables for a tagging system:
CREATE TABLE tags (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
CREATE INDEX tags_name_idx ON tags(name);
CREATE TABLE tagged_items (
tag_id INT,
item_id INT
);
CREATE INDEX tagged_items_tag_id_idx ON tagged_items(tag_id);
CREATE INDEX tagged_items_item_id_idx ON tagged_items(item_id);
CREATE TABLE items (
id SERIAL PRIMARY KEY,
content VARCHAR(255)
);
The user's boolean expression query "tag1 AND tag2" in SQL is:
SELECT items.* FROM items
INNER JOIN tagged_items AS i1 ON (items.id = i1.item_id) INNER JOIN tags AS t1 ON (i1.tag_id = t1.id)
INNER JOIN tagged_items AS i2 ON (items.id = i2.item_id) INNER JOIN tags AS t2 ON (i2.tag_id = t2.id)
WHERE t1.name = 'tag1' AND t2.name = 'tag2';
How do you translate other queries with boolean expressions, such as "tag1 OR tag2 AND tag3" ...or even more complex queries such as "tag1 AND (tag2 OR tag3) AND NOT tag4 OR tag5" to SQL?