简体   繁体   中英

mySQL - Nested Select return list?

I'm trying to write a bit of mySQL but the brain seems to not be working today. I have two tables, with the following structure.

Table 1 : id, name, details

Table 2 : id, type, value

The id links both tables.

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:

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.

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.

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.

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