在where子句中选择,访问当前父选择列

时间:2012-03-29 14:47:19

标签: mysql sql subquery

我有一个查询,其中包含一个select语句的where子句。我现在的问题是,如何访问父母的select数据。

示例:

select * from TABLE_1 as t1 INNER JOIN TABLE_2 as t2
where (... and ...) OR 
      (not exists(select * from TABLE_3 as t3 
                                inner join TABLE_1 ON t3.t1_id = t1.id

最后一行是发生错误的地方:t1.id is not a column

如何从表t1访问当前值? 我正在使用MySql 5.1

2 个答案:

答案 0 :(得分:1)

SELECT
  *
FROM
  TABLE_1 as t1 
  INNER JOIN TABLE_2 as t2 ON
    t2.PK = t1.FK --Whatever your keys are
WHERE
  (... and ...)
  OR
  (
  NOT EXISTS (select * from TABLE_3 as t3 WHERE t3.t1_id = t1.id)
  )

答案 1 :(得分:0)

首先,您需要声明TABLE_1上的JOIN TABLE_2。

SELECT *
FROM TABLE_1 AS t1 
INNER JOIN TABLE_2 AS t2 ON t2.t1_id = t1.id

t1.id = t2.t1_id只是一个示例,您需要决定您希望加入哪些列。然后在WHERE子句中,您不必再次在TABLE_1上INNER JOIN,因为您已经从中选择了它。

SELECT *
FROM TABLE_1 AS t1 
INNER JOIN TABLE_2 AS t2 ON t2.t1_id = t1.id
WHERE (... AND ...) OR 
(
    NOT EXISTS
    (
        SELECT * 
        FROM TABLE_3 AS t3 
        WHERE t3.t1_id = t1.id
    )
)