Is it possible with MySQL to search for a value and with its results use those to complete the search in one statement?

A little confused with how I’d do this at all in a single statement. If it’s possible?

name type domain ip
Donny 0
Donny 0
Donny 1 null
Donny 2 null
Donny 1 null
Lisa 0
Lisa 1 null
Lisa 2 null

I would like to have my Virtual [email protected] to see it belongs to Donny and Lisa, and the returned result would be their server domains (type 0).

I can achieve this with multiple statements but was curious if it could be done with single statements and with that unsure how! Appreciate any insight on this.

I think I got it working, this is what I have thus far!

SELECT results.domain, results.owner
    SELECT domain, ip, owner, type
    FROM server
    WHERE owner IN (SELECT owner FROM server WHERE ip=?)
) AS results WHERE results.type=0;

So if I search, I am returned

name domain

Seems to do what I want very clean/stealthy but wondering if it can be done better than this. 😐


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Hey mate absolutely it can.

You can use the result set from 1 SQL query in theFROM statement of another Query.

Select * from (Select name from 'Table' where domain = "");

This article will take you further:

You can also use nested SQL in the WHERE clause too

Method 2

Based on your comment you can use this two methods (maybe there are other methods).

A. You can use subquery for the names

select name,type,domain
from test_tbl 
where name in ( select name 
                from test_tbl 
                where ip='')
and type='0';

B. You can use inner join but in this case, I do not recommend it.

from test_tbl t1
inner join
  select name,type 
  from test_tbl 
  where ip=''
) t2 on
and t1.type='0';


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x