简体   繁体   中英

match multiple columns to multiple-row subquery?

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 JOIN on both a and b :

SELECT
  path
FROM 
   tb1
   INNER JOIN tb2 ON tb1.a = tb2.a AND tb1.b = tb2.b
/* add your condition to the WHERE clause */
WHERE tb2.value < v1

The use cases for subqueries in the SELECT list or WHERE clause can very often be handled instead using some type of JOIN . The join will frequently be faster than the subquery, owing to the fact that when using a SELECT or WHERE subquery, the subquery may need to be performed for each row returned, rather than only once.

Beyond the MySQL documentation on JOIN s linked above, I would also recommend Jeff Atwood's Visual Explanation of SQL JOINs

INNER JOIN will do the trick.

You just need two ON criteria in order to match both the a and b values, like so:

SELECT path
FROM tb1
INNER JOIN tb2 ON tb1.a = tb2.a AND tb1.b = tb2.b
WHERE tb2.value < v1

You can limit your result set this way:

select
 path 
from tb1
 where
 a=(select a from tb2 where value < v1 LIMIT 1) 
and
 b=(select b from tb2 where value < v1 LIMIT 1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM