Skip to content

Instantly share code, notes, and snippets.

@qcom
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qcom/ac21d995366fa2e3db1b to your computer and use it in GitHub Desktop.
Save qcom/ac21d995366fa2e3db1b to your computer and use it in GitHub Desktop.
CREATE TABLE IF NOT EXISTS items (
id serial PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS industries (
id serial PRIMARY KEY,
name text UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS items_industries (
item integer REFERENCES items(id),
industry integer REFERENCES industries(id)
);
CREATE TABLE IF NOT EXISTS categories (
id serial PRIMARY KEY,
name text UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS items_categories (
item integer REFERENCES items(id),
industry integer REFERENCES industries(id)
);
-- now-functioning query
SELECT item_id, title, industries, array_agg(name)
FROM
items_categories ic
INNER JOIN (SELECT items.id as item_id, title, array_agg(industries.name) as industries FROM
items INNER JOIN items_industries ON items.id = items_industries.item INNER JOIN industries ON industries.id = industry
WHERE items.id = 31 GROUP BY items.id) jt
ON (ic.item = jt.item_id)
INNER JOIN categories ON category = categories.id GROUP BY item_id, title, industries;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment