Question

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.

Was it helpful?

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:

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)

OTHER TIPS

You can write it as:

select
  ca.*
from
  candies ca
where
  ca.color_code = (
    select co.color_code
    from colors co
    where co.color_value = 'blue'
  )

but there shouldn't be any difference. Actually the join approach is a bit more robust.

What's more - consider getting rid of the colors table at all, and using just color_values instead of codes. It's actually more efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top