简体   繁体   中英

Using the same table on SELECT and WHERE clause

Simple case

I have a simple table where one column is the PK of another element of the same table, as follows:

    id     |  something   | parent_id
___________|______________|____________
     1     |   colors     |  null
     2     |   red        |  1
     3     |   green      |  1
     4     |   blue       |  1
    ...    |   ...        | ...

Task

I wanted to get all elements that have the parent_id of the element that matches a condition. Let's suppose the parent element should have something='colors'

Expected Result

    id     |  something   | parent_id
___________|______________|____________
     2     |   red        |  1
     3     |   green      |  1
     4     |   blue       |  1

After looking around on StackOverflow I have tried:

SELECT * FROM my_table WHERE 
   parent_id=(SELECT id FROM my_table WHERE something='colors')

and also:

SELECT * FROM my_table as t1 WHERE
   t1.parent_id=(SELECT id FROM my_table as t2 WHERE t2.something='colors')

but I get this error:

Error: You have an error in your SQL syntax

The reason was a missing ; on the previous file that was being merged before mine. The above queries do work ...


This is not my field and I know that a " solution "( ? ) ( used by others in the project ) could be:

SELECT * FROM my_table WHERE 
    parent_id=(SELECT id FROM (SELECT * FROM my_table) AS t1 WHERE something='colors')

but I don't really like this


Thanks anyone for the help. I know we should LIMIT 1 or use IN to prevent errors, I was trying to simplify the sintax as most as I could.

use exists

SELECT t1.* FROM table_name t1
WHERE EXISTS(SELECT 1 FROM table_name t2 WHERE t1.id=t2.parent_id)

You can do :

SELECT t.*
FROM table t
WHERE EXISTS(SELECT 1 FROM table t1 WHERE t1.id = t.parent_id AND t1.something = 'colors');

You can get it with a simple JOIN:

SELECT T1.* FROM my_table AS T1 
JOIN my_table AS T2 ON T1.parent_id = T2.id
WHERE T2.something='colors';

This technique is known as a SELF JOIN. Here for more details.

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