mysql将子查询存储在列中并执行where condition

时间:2016-10-18 15:20:42

标签: mysql sql

我在mysql中执行子查询,就像

select col1, col2 , (select col3 from table2) as 'data'
from table1 
where not data is null

我应该如何在where子句中获取数据。它是否可能

2 个答案:

答案 0 :(得分:2)

一种方法是:

SELECT *
FROM (
       select col1, col2 , (select col3 from table2) as 'data'
       from table1 
)t
WHERE data IS NOT NULL

正如您在那里看到的那样,我为您的查询创建了派生表t,现在您的查询结果被视为表(临时表)并且列为col1,col2和 col3 ,使用此结果集,我们可以访问where子句中的col3。

注意 - 假设select col3 from table2根据OP的评论返回单个值

答案 1 :(得分:0)

使用cross join

select t1.col1, t1.col2, t2.col3 as data
from table1 t1 cross join
     (select col3 from table2) t2
where t2.col3 is not null;