简体   繁体   English

在多个条件下引用子查询

[英]Referencing sub-query in multiple conditions

I have a single table called employees :我有一个名为employees的表:

id     |    name    |    born    |    stinky
-------------------------------------------------
1          Chris        1982            1
2          Chris        1982            1
3           Bob         1982            0
4          Chris        1982            1

I want to grab rows 2, 4 based on the following condition:我想根据以下条件抓取第 2、4 行:

SELECT 
    id,name,born,stinky
FROM
    employees
WHERE
    name=(SELECT name FROM employees WHERE id=1)
        AND
    born=(SELECT born FROM employees WHERE id=1)
        AND
    stinky=(SELECT stinky FROM employees WHERE id=1)
        AND
    id != 1

Is there a way to optimize this to only execute one single sub-query, and then reference the sub-query data multiple times?有没有办法优化这个只执行一个子查询,然后多次引用子查询数据? For example, something like this:例如,像这样:

SELECT 
    id,name,born,stinky
FROM
    employees
SUBQUERY
    (SELECT name FROM employees WHERE id=1) AS XX
WHERE
    name=XX.name
        AND
    born=XX.born
        AND
    stinky=XX.stinky
        AND
    id != 1

You can use the subquery only once:您只能使用一次子查询:

SELECT id,name,born,stinky
FROM employees
WHERE (name,born,stinky) = (SELECT name,born,stinky FROM employees WHERE id=1)
  AND id <> 1

Another way to do it is with a join:另一种方法是加入:

SELECT e.id,e.name,e.born,e.stinky
FROM employees e
INNER JOIN (SELECT * FROM employees WHERE id=1) t
ON (t.name,t.born,t.stinky) = (e.name,e.born,e.stinky) AND t.id <> e.id

See the demo .请参阅演示
Results:结果:

id ID name姓名 born出生 stinky臭的
2 2 Chris克里斯 1982 1982年 1 1
4 4 Chris克里斯 1982 1982年 1 1

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

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