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

时间:2019-04-11 10:13:51

标签: mysql sql

简单案例

我有一个简单的表,其中一列是同一表中另一个元素的PK,如下所示:

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

任务

我想获取所有具有条件的元素parent_id的元素。 假设父元素应具有something='colors'

预期结果

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

环顾StackOverflow之后,我尝试了:

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

还有:

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

但我收到此错误:

  

错误:您的SQL语法有错误

原因是在我的文件之前被合并的先前文件中缺少;。以上查询确实有效 ...


这不是我的领域,我知道一个“ 解决方案”()(项目中其他人使用的 )可能是:

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

但是我不是很喜欢


感谢任何人的帮助。 我知道我们应该LIMIT 1或使用IN来防止错误,我正尽最大努力简化sintax。

3 个答案:

答案 0 :(得分:1)

使用存在

['The UNDERCOVER x Nike SFB Mountain Pack Gets a Release Date', 'The UNDERCOVER x Nike SFB Mountain Surfaces in "Dark Obsidian/University Red"', 'A First Look at UNDERCOVER’s Nike SFB Mountain Collaboration', "Here's Where to Buy the UNDERCOVER x Gyakusou Nike Running Models", 'Take Another Look at the Upcoming UNDERCOVER x Nike Daybreak', "Take an Official Look at GYAKUSOU's SS19 Footwear and Apparel Range", 'UNDERCOVER x Nike Daybreak Expected to Hit Shelves This Summer', "The 10 Best Sneakers From Paris Fashion Week's FW19 Runways", "UNDERCOVER FW19 Debuts 'A Clockwork Orange' Theme, Nike & Valentino Collabs", 'These Are the Best Sneakers of 2018']

答案 1 :(得分:1)

您可以:

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

答案 2 :(得分:1)

您可以通过简单的JOIN来获得它:

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

此技术称为“自连接”。 Here了解更多详情。