简体   繁体   English

在SELECT和WHERE子句上使用相同的表

[英]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: 我有一个简单的表,其中一列是同一表的另一元素的PK,如下所示:

    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. 我想获取所有具有与条件匹配的元素的parent_id的元素。 Let's suppose the parent element should have something='colors' 让我们假设父元素应该有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: 在环顾StackOverflow之后,我尝试了:

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 错误:您的SQL语法有错误

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. 我知道我们应该使用LIMIT 1或使用IN来防止错误,我正在尽我最大的努力简化sintax。

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: 您可以通过简单的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. 在这里了解更多详情。

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

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