使用INNER JOIN查询返回空结果

时间:2018-04-16 18:05:47

标签: sql sqlite

我有这两个表:

联系

id | datetime   | book_id | name         |
1    2018-04-16     1        foo   
2    2018-04-16     1        another foo
3    2018-04-16     1        foo2
4    2018-03-01     1        foo3

详细

id  | datetime | book_id |  
 1   2018-04-16    1

我想选择datetime 2018-04-16和book_id 1的记录,结果必须是:

1    2018-04-16     1        foo   
2    2018-04-16     1        another foo
3    2018-04-16     1        foo2
4    2018-03-01     1        foo3
1   2018-04-16      1

我的查询是:

SELECT * FROM Contact
         INNER JOIN Details
         ON Contact.book_id = Details.book_id
         WHERE Contact.book_id = :book_id AND 
         Contact.datetime BETWEEN :start_date AND :end_date

查询返回没有行,为什么我做错了?

2 个答案:

答案 0 :(得分:0)

如果您使用单个日期,则应使用= not between之间需要范围

SELECT * FROM Contact
INNER JOIN Details  ON Contact.book_id = Details.book_id
 WHERE Contact.book_id = 1  
         Contact.datetime = '2018-04-16'  

或使用有效范围(例如仅用于测试)

SELECT * FROM Contact
INNER JOIN Details  ON Contact.book_id = Details.book_id
 WHERE Contact.book_id = 1  
         Contact.datetime  between   '2018-04-15'   and  '2018-04-17' 

答案 1 :(得分:0)

您的约会可能有时间成分。因此,尝试在使用between之前将值转换为日期:

SELECT *
FROM Contact c INNER JOIN
     Details d
     ON c.book_id = d.book_id
WHERE c.book_id = :book_id AND 
      DATE(c.datetime) BETWEEN :start_date AND :end_date;