我的mySQL查询有问题

时间:2011-03-22 05:36:17

标签: mysql

SELECT t.id, t.active, t.off, t.duration, t.user
FROM table t
WHERE t.active = '0000-00-00 00:00:00'
OR t.duration != '0'
AND t.user = '1'
AND t.off = '0000-00-00 00:00:00'
LIMIT 0 , 30

基本上它忽略了t.off部分,有什么不对吗?

谢谢=)

(查询是为了示例目的而编辑的,真正的查询与此类似,但与其他表名称等)

== [更新] ==

SELECT t.active, t.off, t.duration, t.user
FROM table t
WHERE (
    t.active = '0000-00-00 00:00:00'
    OR t.duration != '0'
)
AND t.user = '1'
AND t.off = '0000-00-00 00:00:00'
LIMIT 0 , 30
UNION ALL
SELECT c.active, c.off, c.duration, c.user
FROM chair c
WHERE (
    c.active = '0000-00-00 00:00:00'
    OR c.duration != '0'
)
AND c.user = '1'
AND c.off = '0000-00-00 00:00:00'

1 个答案:

答案 0 :(得分:0)

您应该使用括号,对条件and / or进行分组,以确保按照您想要的顺序对其进行评估。

例如,您想要关注:

SELECT t.id, t.active, t.off, t.duration, t.user
FROM table t
WHERE t.active = '0000-00-00 00:00:00'
OR (
    t.duration != '0'
    AND t.user = '1'
    AND t.off = '0000-00-00 00:00:00'
)
LIMIT 0 , 30

或以下内容:

SELECT t.id, t.active, t.off, t.duration, t.user
FROM table t
WHERE (
    t.active = '0000-00-00 00:00:00'
    OR t.duration != '0'
)
AND t.user = '1'
AND t.off = '0000-00-00 00:00:00'
LIMIT 0 , 30

或者别的什么?


使用括号将使您的查询更容易阅读 - 并将有助于确保正确评估条件。