简体   繁体   English

匹配多列到多行子查询?

[英]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.). 我仍在学习有关mySQL的知识(实际上我仍然只能接受基本查询,计数,排序等)。 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. 我想对a,b与tb2上的不同查询匹配的tb1中的每一行返回“ path”的查询。 In bad mysql, it would be something like: 在糟糕的mysql中,它将类似于:

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 请注意,通过in交换= by还不够好,因为对于a,b值的组合( select a,b from tb2 where value < v1未返回)是不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). 基本上,我已经基于tb2在(a,b)空间中确定了一个有趣的区域,并想研究tb1在该区域内的行为(如果可以更清楚地了解)。

thank you :) 谢谢 :)

This is a job for an INNER JOIN on both a and b : 这是一个工作一个INNER JOIN两个ab

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 . SELECT列表或WHERE子句中的子查询的用例通常可以使用某种类型的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. 由于使用SELECTWHERE子查询时,可能需要为返回的每一行执行子查询,而不是只执行一次,因此联接通常会比子查询快。

Beyond the MySQL documentation on JOIN s linked above, I would also recommend Jeff Atwood's Visual Explanation of SQL JOINs 除了上面链接的关于JOIN的MySQL文档之外,我还建议Jeff Atwood的SQL JOIN的可视化解释。

INNER JOIN will do the trick. INNER JOIN将解决问题。

You just need two ON criteria in order to match both the a and b values, like so: 您只需要两个ON条件即可同时匹配a和b值,如下所示:

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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