I’m very much still learning about mySQL (am still really only comfortable with basic queries, count, order by etc.). It is very likely that this question has been asked before, however either I don’t know what to search for, or I’m too much of a novice to understand the answers:
I have two tables:
tb1 (a,b,path)
tb2 (a,b,value)
I would like to make a query that returns “path” for each row in tb1 whose a,b matches a different query on tb2. In bad mysql, it would be something like:
select
path
from tb1
where
a=(select a from tb2 where value < v1)
and
b=(select b from tb2 where value < v1);
however, this doesn’t work, as the subqueries are returning multiple values. Note that exchanging = by in is not good enough, as that would be true for combinations of a,b-values that are not returned by select a,b from tb2 where value < v1
Basically, I have identified an interesting area in (a,b)-space based on tb2, and would like to study the behavior of tb1 within that area (if that makes it any clearer).
thank you 🙂
This is a job for an
INNER JOINon bothaandb:The use cases for subqueries in the
SELECTlist orWHEREclause can very often be handled instead using some type ofJOIN. The join will frequently be faster than the subquery, owing to the fact that when using aSELECTorWHEREsubquery, the subquery may need to be performed for each row returned, rather than only once.Beyond the MySQL documentation on
JOINs linked above, I would also recommend Jeff Atwood’s Visual Explanation of SQL JOINs