谁能帮我解决这个问题?我一直在尝试查询这个,但我不断收到错误。
mysql代码:
SELECT * FROM
(
SELECT BU.*, BD.BOOK_TITLE AS BOOK_TITLE, BD.BOOK_COMPANY AS COMPANY,
BD.RETURN_DATE AS RETURN
FROM BOOK_USER BU
INNER JOIN BOOKING_DETAIL BD ON (BU.USR_ID = BD.USR_ID)
UNION
SELECT BU.*, "NEW REGISTERED" AS BOOK TITLE, 'RENT-A-BOOK' AS COMPANY,
BU.REGISTER_DATE AS RETURN
FROM BOOK_USER BU
) AS BU
GROUP BY BU.USR_ID
表:
BOOK_USER
+---------+----------+---------------+
| USR_ID | USR_NAME | REGISTER_DATE |
+---------+----------+---------------+
| 1 | john | 2011-09-20 |
+---------+----------+--------------+
| 2 | jane | 2011-12-05 |
+---------+----------+--------------+
| 3 | doe | 2012-02-16 |
+---------+----------+--------------+
| 4 | mary | 2012-02-02 |
+---------+----------+--------------+
BOOKING_DETAIL
+---------+----------+------------+-----------+--------------+
| BOOK_ID | USR_ID | BOOK_TITLE | COMPANY | RETURN_DATE |
+----------+--------+-------------+-----------+--------------+
| 1 | 1 | DEAR JOHN |ABC PVT LMT| 2011-11-01 |
+---------+---------+-------------+-----------+--------------|
| 2 | 1 | LUCKY | DEF | 2012-03-18 |
+---------+---------+-------------+-----------+--------------|
| 3 | 1 | THE RISE | GHI | 2012-06-12 |
+---------+---------+-------------+-----------+--------------|
| 4 | 2 | HELLO | TIMES | 2012-01-11 |
+---------+---------+-------------+-----------+--------------|
| 5 | 2 | SHOPAHOLIC | | 2012-08-31 |
+---------+---------+-------------+-----------+--------------|
| 6 | 3 | LOST | | 2012-06-20 |
+---------+---------+-------------+-----------+--------------|
结果应返回最新的RETURN_DATE 并按 USR_ID 排序。
例如:
- 约翰,崛起,GHI,2012-06-12
- 简,购物狂,出租书,2012-08-31
- 能源部,丢失,租借一本书,2012-06-20
- 玛丽, 新注册, 出租书, 2012-02-02