简体   繁体   English

MySQL-嵌套选择返回列表?

[英]mySQL - Nested Select return list?

I'm trying to write a bit of mySQL but the brain seems to not be working today. 我正在尝试编写一些mySQL,但是今天大脑似乎无法正常工作。 I have two tables, with the following structure. 我有两个表,结构如下。

Table 1 : id, name, details 表1: ID,名称,详细信息

Table 2 : id, type, value 表2: id,类型,值

The id links both tables. id链接两个表。

So what I'm trying to do is something like the following, where I return a record based on the results of a nested select. 因此,我要尝试执行的操作类似于以下内容,其中我基于嵌套选择的结果返回记录。

SELECT * FROM table1 WHERE name = 'someName' AND id = (SELECT id FROM table2 WHERE type = 'type1')

Anyone have any ideas? 有人有想法么?

Try this as a solution 试试这个作为解决方案

SELECT * 
FROM table1 
INNER JOIN table2 
  ON table1.id = table2.id 
  AND table2.type = 'type1' 
WHERE table1.name = 'someName'

This is what a JOIN is for: 这是JOIN的作用:

SELECT * FROM table1 JOIN table2 USING (id)
WHERE type = 'type1' AND name = 'someName'

By the way, as far as I can tell there is no reason for these to be in separate tables unless the id can be duplicated, which would probably be bad. 顺便说一句,据我所知,除非id可以重复,否则没有理由将它们放在单独的表中,这可能是不好的。

That query is executing from right to left. 该查询是从右到左执行的。 It is returning the rows from table2 where type = 'type1', maybe 1 or more rows, then it is executing the first query (outer) off the results of the inner query (table2) and returning all the rows where the id from the outer query (table1) exists in the results from the inner query (table2), if there are no results the query engine terminates the query, if there are results it will now evaluate those results based on the where clause (name = 'someName') of the outer query (table1), if results are found they get returned, otherwise the query engine terminates here. 它从table2返回类型='type1'的行,可能是1或更多行,然后从内部查询(table2)的结果执行第一个查询(外部),并返回ID为内部查询(table2)的结果中存在外部查询(table1),如果没有结果,查询引擎将终止查询;如果有结果,它现在将基于where子句(name ='someName' )(外部表(表1)),如果找到结果,则返回结果,否则查询引擎将在此处终止。

Basically we write queries in this order; 基本上,我们按此顺序编写查询; select from where group by having order by 通过排序从中选择组

however the processing order is like this; 但是处理顺序是这样的; from where group by having select order by 通过选择顺序从哪里分组

When the query engine executes a query, it goes through each phase on one or more tables as the input and returns a virtual table as the output, the output of one phase of the query is the input for the next phase of the query. 当查询引擎执行查询时,它将经过一个或多个表的每个阶段作为输入,并返回一个虚拟表作为输出,查询的一个阶段的输出就是查询的下一阶段的输入。

Hope this helps you understand the query better. 希望这可以帮助您更好地了解查询。

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

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