更好的mysql查询替代方案

时间:2015-01-29 06:23:29

标签: mysql

我有一个表test1,它的数据如下所示:

enter image description here

现在我不想从days>0 in prod_year 2012表中选择test1的记录,所以我在下面的查询中使用:

select * from test1
where id in (select id from test1 where pyear=2012 and 
(days<=0 or days is null)) OR id in (select id from test1 where pyear!=2012);

但是当解释上面的查询时它显示了DEPENDENT SUBQUERY

enter image description here

有没有更好的方法来编写此查询?

提前致谢。

4 个答案:

答案 0 :(得分:1)

这应该做的工作:

select * from test1 where (pyear=2012 and (days<=0 or days is null)) or pyear<>2012

答案 1 :(得分:1)

是。有。 UNION可以帮助您:

SELECT * FROM test1 WHERE pyear=2012 AND (days<=0 OR days IS NULL)
UNION
SELECT * FROM test1 WHERE pyear!=2012

在defference列上使用INDEX时,即使存在索引列,某些MySQL旧版本(小于4.1,我猜)也无法使用OR(这意味着完全扫描)。在这种情况下,应使用UNION

答案 2 :(得分:0)

select * from test1 where days <= 0 && pyear >= 2012

这将起作用

答案 3 :(得分:0)

select * from test1 where days > 0 && pyear >= 2012
相关问题