在两个给定日期之间获取行(在这些日期包含行)

时间:2014-01-13 09:35:46

标签: mysql sql date

我知道这应该很简单,但事实证明它非常复杂,我有两张桌子:

USERS id | name | url

COMMENTS id | id_user | text | lang | date(datetime)

我想要检索这两个给定日期(包括两个日期)之间的所有记录(评论)我已经尝试过两种不同的方式,但它们没有按照规定工作,在应该的地方没有返回结果:

选项A 以下句子什么都不返回,并且有评论,这两条评论应该出现,因为日期是'2014-01-09 16:34:58'和'2014-01-13 10:09:24'

SELECT
  comments.text,
  users.url,
  users.name
FROM comments
  JOIN users
    ON comments.id_user = users.id
WHERE comments.date BETWEEN '2014-01-13'
    AND '2014-01-09'
    AND comments.lang = 'es'
ORDER BY comments.date DESC

选项B 以下句子返回在'2014-01-09'日写的通知,但不是在'2013-01-09'上写的那些

SELECT
  comments.text,
  users.url,
  users.name
FROM comments
  JOIN users
    ON comments.id_user = users.id
WHERE comments.date <= '2014-01-13'
    AND comments.date > '2014-01-09'
    AND comments.lang = 'es'
ORDER BY comments.date DESC

我做错了什么?

2 个答案:

答案 0 :(得分:0)

而不是BETWEEN使用此

SELECT
  comments.texto,
  usuarios.url,
  users.nombre
FROM comments
  JOIN usuarios
    ON comments.id_usuario = users.id
WHERE DATE(comments.date) <= '2014-01-14'
    AND DATE(comments.date) >= '2014-01-09'
    AND comments.lang = 'es'
ORDER BY comments.fecha DESC

OR

SELECT
  comments.texto,
  usuarios.url,
  users.nombre
FROM comments
  JOIN usuarios
    ON comments.id_usuario = users.id
WHERE comments.date <= '2014-01-14  59:59:59'
    AND comments.date >= '2014-01-09 00:00:00'
    AND comments.lang = 'es'
ORDER BY comments.fecha DESC

答案 1 :(得分:0)

改变这个:

WHERE comments.date BETWEEN '2014-01-13' AND '2014-01-09'

对此:

WHERE comments.date BETWEEN '2014-01-09' AND '2014-01-13 23:59:59'

MySQL BETWEEN子句要求 min max 参数正确排序,因此必须先指定较小​​的值。其次,要包含2014-01-13的记录,您需要添加时间部分(datetime中的时间部分不包含毫秒,因此检查23:59:59就足够了)。或者你可以写:

WHERE comments.date >= '2014-01-09'
  AND comments.date <  '2014-01-13' + INTERVAL 1 DAY
                   --  ^---------------------------^ evaluates to 2014-01-14