MySQL大于日期返回的日期小于给定的日期

时间:2014-03-19 19:05:17

标签: php mysql sql

我遇到问题MySQL给我一个日期少于今天日期的结果,当时我正在使用NOW(),CURDATE()和php日期(' Ym-d',strtotime(&#) 39;现在'));以下是我的查询和我的结果

SELECT j.*
       ,j.id AS job_id
       ,c.company_name
       ,images.*
    FROM jobs j
       ,companies c
       ,images images
    WHERE j.user_id = c.user_id
        AND images.user_id = j.user_id
        AND j.description LIKE '%php%'
        OR j.title LIKE '%php%'
        AND j.start_date <= '2014-03-19'
        AND j.end_date > '2014-03-19'
        AND j.published = 1
    GROUP BY j.id ASC
    ORDER BY j.featured DESC

RESULT

start_date: 2013-12-08     end_date:  2014-01-08

是否有理由将这个结果还给我?

4 个答案:

答案 0 :(得分:2)

您可能需要将查询的OR相关部分更改为此...

AND (j.description LIKE '%php%'  OR  j.title LIKE '%php%')

请参阅OR优先级低于AND(与+运算符的优先级相同,低于*一个优先级。所以它基本上将整个条件分为两部分,如果这些部分的任何通过检查,则整个条件通过检查。

答案 1 :(得分:1)

您的WHERE子句中可能存在运算符优先级问题。

由于AND优先于OR,因此您实际上是这样做的:

WHERE
(j.user_id = c.user_id
AND images.user_id = j.user_id
AND j.description LIKE '%php%')
OR
(j.title LIKE '%php%'
AND j.start_date <= '2014-03-19' 
AND j.end_date > '2014-03-19'
AND j.published =1)

因此,将选择任何满足OR语句一半的记录。

我猜你想要这样做:

WHERE
j.user_id = c.user_id
AND images.user_id = j.user_id
AND (j.description LIKE '%php%' OR j.title LIKE '%php%')
AND j.start_date <= '2014-03-19' 
AND j.end_date > '2014-03-19'
AND j.published =1

我的建议是养成在所有混合操作符的情况下使用括号的习惯,这样你和其他任何可能阅读代码的人都会清楚地知道意图是什么。

有关MySQL中运算符优先级的更多信息,请查看以下链接:

https://dev.mysql.com/doc/refman/5.6/en/operator-precedence.html

答案 2 :(得分:0)

AND优先于OR。这意味着不是做

SELECT j . * , j.id AS job_id, c.company_name, images . *
FROM jobs j, companies c, images images
WHERE j.user_id = c.user_id
AND images.user_id = j.user_id
AND ( j.description LIKE '%php%'OR j.title LIKE '%php%' )
AND j.start_date <= '2014-03-19' 
AND j.end_date > '2014-03-19'
AND j.published =1
GROUP BY j.id ASC
ORDER BY j.featured DESC
似乎条件更有意义。你正在执行

SELECT j . * , j.id AS job_id, c.company_name, images . *
FROM jobs j, companies c, images images
WHERE ( 
   j.user_id = c.user_id
   AND images.user_id = j.user_id
   AND j.description LIKE '%php%' 
)
OR 
(
   j.title LIKE '%php%' 
   AND j.start_date <= '2014-03-19' 
   AND j.end_date > '2014-03-19'
   AND j.published = 1 
)
GROUP BY j.id ASC
ORDER BY j.featured DESC

所以你的错误日期可能来自上面查询中where子句的第一部分。

答案 3 :(得分:0)

您正在混合和/或语句,订单可能会在选择事物的方式上发生变化

SELECT j . * , j.id AS job_id, c.company_name, images . *
FROM jobs j, companies c, images images
WHERE j.user_id = c.user_id
AND images.user_id = j.user_id
AND j.description LIKE '%php%'
OR (j.title LIKE '%php%'
AND j.start_date <= '2014-03-19' 
AND j.end_date > '2014-03-19'
AND j.published =1)
GROUP BY j.id ASC
ORDER BY j.featured DESC

尝试将括号放在正确的位置。希望有效。祝你好运