Last active
February 22, 2017 01:07
-
-
Save jamesplease/878eaf98713bdb98dfea2c8014c2e437 to your computer and use it in GitHub Desktop.
Guest relationship support queries for api-pls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Select one | |
WITH toppings_of_pizzas AS ( | |
SELECT | |
pizza_id, | |
array_agg(topping_id) AS topping_ids | |
FROM pizza_topping | |
WHERE pizza_id=1 | |
GROUP BY pizza_id | |
) | |
SELECT | |
pizza.*, | |
(SELECT topping_ids FROM toppings_of_pizzas) AS topping_ids | |
FROM pizza | |
WHERE id=1; | |
-- Select all | |
\timing ON | |
WITH toppings_of_pizzas AS ( | |
SELECT | |
pizza_id, | |
array_agg(topping_id) AS topping_ids | |
FROM pizza_topping | |
GROUP BY pizza_id | |
) | |
SELECT | |
pizza.*, | |
(SELECT topping_ids FROM toppings_of_pizzas WHERE pizza.id = toppings_of_pizzas.pizza_id) AS topping_ids | |
FROM pizza; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Select one | |
\timing ON | |
WITH cats_by_owner AS ( | |
SELECT | |
owner_id, | |
array_agg(id) AS cat_ids | |
FROM cat | |
WHERE owner_id=1 | |
GROUP BY owner_id | |
) | |
SELECT | |
person.*, | |
(SELECT cat_ids FROM cats_by_owner) AS cat_ids | |
FROM person | |
WHERE id=1; | |
-- Select all | |
\timing ON | |
WITH cats_by_owner AS ( | |
SELECT | |
owner_id, array_agg(id) AS cat_ids | |
FROM cat | |
GROUP BY owner_id | |
) | |
SELECT | |
person.*, | |
(SELECT cat_ids FROM cats_by_owner WHERE person.id = cats_by_owner.owner_id) AS cat_ids | |
FROM person; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This is the original query. It works great for fetching one person | |
-- at a time, but isn't so good with fetching many. | |
WITH | |
cat_ids AS ( | |
SELECT array( | |
SELECT id | |
FROM cat | |
WHERE owner_id=1 | |
) AS pet_ids | |
) | |
SELECT * | |
FROM person, cat_ids | |
WHERE person.id = 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment