patternsqlMinor
Query PostgreSQL 9.0 table on foreign key value?
Viewed 0 times
postgresqlqueryforeignvaluetablekey
Problem
Noob-type question:
Say I have two tables, candies and colors. The colors table holds just code/value pairs like 01 yellow, 02 blue, 03 green, etc. and is referenced in the candies table by code.
How do I query the candies table for all blue candies without an explicit join? For two years now I've been writing these queries with joins, like:
SELECT * FROM candies a JOIN colors o ON(a.color_code = o.color_code)
WHERE o.color_value = 'blue';
I'm certain every time that I'm bringing a gun to a knife fight, but my googling has been fruitless.
Thanks.
Say I have two tables, candies and colors. The colors table holds just code/value pairs like 01 yellow, 02 blue, 03 green, etc. and is referenced in the candies table by code.
How do I query the candies table for all blue candies without an explicit join? For two years now I've been writing these queries with joins, like:
SELECT * FROM candies a JOIN colors o ON(a.color_code = o.color_code)
WHERE o.color_value = 'blue';
I'm certain every time that I'm bringing a gun to a knife fight, but my googling has been fruitless.
Thanks.
Solution
"I'm certain every time that I'm bringing a gun to a knife fight, but my googling has been fruitless." What makes you think that? RDBMSs are built to 'join'
If your aim is to make you SQL more readable then you might prefer the 'using' syntax:
alternatively, seeing as you are hard-coding 'blue' into your query, you could consider hard-coding the code instead:
but this will decrease readability unless in your real-world scenario the codes are descriptive (eg 'BLU' for blue)
If your aim is to make you SQL more readable then you might prefer the 'using' syntax:
SELECT * FROM candies JOIN colors USING(color_code) WHERE color_value = 'blue';alternatively, seeing as you are hard-coding 'blue' into your query, you could consider hard-coding the code instead:
SELECT * FROM candies WHERE color_code = '02';but this will decrease readability unless in your real-world scenario the codes are descriptive (eg 'BLU' for blue)
Code Snippets
SELECT * FROM candies JOIN colors USING(color_code) WHERE color_value = 'blue';SELECT * FROM candies WHERE color_code = '02';Context
StackExchange Database Administrators Q#2431, answer score: 3
Revisions (0)
No revisions yet.