“WHERE IN”子句中的SQL查询

时间:2011-08-09 11:36:18

标签: mysql sql

select * from tablename 
     where id in(select id from tablename2 where condition UNION select -1)

使用select -1是否可以,就好像内部查询不会产生任何错误一样。是否可行?

3 个答案:

答案 0 :(得分:1)

imho,inner-select远非理想(慢)

根据您发布的SQL,an inner join将执行此操作

select * 
from tablename as t1
inner join tablename2 as t2
on t1.id=t2.id
where condition; --- your condition

答案 1 :(得分:1)

如果必须使用子查询完成它,那么正确的方法可能是:

SELECT *
FROM tablename AS t1
WHERE EXISTS
    (SELECT id 
     FROM tablename2 AS t2
     WHERE conditions)

答案 2 :(得分:0)

如果查询没有返回任何内容,则不会出错。它只返回一个空的结果集。