我有一个图书馆的数据库,我正在尝试编写一个查询以返回所有五年内未借出的图书
它应该产生这样的东西......
isbn | title | author
------+---------------------+---------------
222 | The Art of the Deal | Trump
444 | Im a cool guy | Forrest Stone
(2 rows)
我有一个books
表,
library6=# SELECT * FROM books;
isbn | title | author
------+---------------------------------------+---------------
111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
222 | The Art of the Deal | Trump
333 | to catch a crook | Robert Muller
444 | Im a cool guy | Forrest Stone
555 | rich i am | Bill Gates
(5 rows)
我有一个交易
表,
library6=# SELECT * FROM transactions;
id | checked_out_date | checked_in_date | user_id | isbn
----+------------------+-----------------+---------+------
1 | 2016-01-01 | 2016-02-01 | 1 | 111
2 | 2016-02-02 | 2016-03-02 | 2 | 111
3 | 2016-03-03 | 2016-05-03 | 3 | 111
5 | 2017-11-29 | 2017-12-04 | 5 | 555
6 | 2017-11-28 | 2017-12-05 | 1 | 333
4 | 2017-12-06 | 2017-12-09 | 4 | 111
5 | 2010-01-01 | 2010-01-02 | 1 | 222
(7 rows)
到目前为止,我已经尝试过,它正确地连接了两个表并返回了从未被借出的书,但错过了 5+ 年前被借出的书。
library6=# SELECT b.title,b.author , b.isbn FROM transactions t
RIGHT OUTER JOIN books b ON t.isbn = b.isbn
WHERE t.isbn IS NULL;
title | author | isbn
---------------+---------------+------
Im a cool guy | Forrest Stone | 444
(1 row)
于是我尝试了一下
library6=# SELECT b.title, t.isbn FROM transactions t
RIGHT OUTER JOIN books b ON t.isbn = b.isbn
WHERE t.checked_out_date >= DATEADD(year, 5, '2017/12/09') AS DateAdd OR
t.isbn IS NULL;
ERROR: syntax error at or near "AS"
LINE 3: ...hecked_out_date >= DATEADD(year, 5, '2017/12/09') AS DateAdd...
理想情况下 我会使用timestamp
自动生成当前日期,但一次一步。
最佳答案
library6=#
SELECT b.title, b.isbn,b.author ,max(t.checked_out_date)
FROM transactions t
RIGHT OUTER JOIN books b ON t.isbn = b.isbn
group by b.isbn, b.title
having max(t.checked_out_date) <= (CURRENT_DATE - INTERVAL '5
years')
PostgreSQL 没有提供dateadd 函数
关于sql - 尝试按日期过滤 SQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735720/