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
表格:
+---------+----------+---------------+
| 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 |
+---------+----------+--------------+
+---------+----------+------------+-----------+--------------+
| 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 |
+---------+---------+-------------+-----------+--------------|
例如:
答案 0 :(得分:0)
查询构成一个子查询,它为每个用户获取最新 RETURN_DATE
。
SELECT a.*, c.BOOK_TITLE, c.RETURN_DATE
FROM book_user a
INNER JOIN
(
SELECT usr_ID, MAX(return_DATE) maxDate
FROM booking_detail
GROUP BY usr_ID
) b ON a.usr_ID = b.usr_ID
INNER JOIN booking_detail c
ON b.usr_ID = c.usr_ID AND
b.maxDate = c.return_DATE
<强>更新强>
使用LEFT JOIN
和COALESCE
SELECT a.USR_ID,
a.USR_NAME,
COALESCE(c.BOOK_TITLE,'RENT-A-BOOK') BOOK_TITLE,
COALESCE(c.RETURN_DATE, a.REGISTER_DATE) RETURN_DATE
FROM book_user a
LEFT JOIN
(
SELECT usr_ID, MAX(return_DATE) maxDate
FROM booking_detail
GROUP BY usr_ID
) b ON a.usr_ID = b.usr_ID
LEFT JOIN booking_detail c
ON b.usr_ID = c.usr_ID AND
b.maxDate = c.return_DATE
答案 1 :(得分:0)
试试:
SELECT *
FROM (
(
SELECT BU.*, BD.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 ALL (
SELECT BU.*, BD.BOOK_TITLE, 'RENT-A-BOOK' AS COMPANY,BD.RETURN_DATE AS RETURN FROM BOOK_USER BU INNER JOIN BOOKING_DETAIL BD ON (BU.USR_ID = BD.USR_ID)
)
) BU
GROUP BY BU.USR_ID
答案 2 :(得分:0)
您可以使用以下查询直接获取输出检查查询:
SELECT BU.*, IFNULL(BD.BOOK_TITLE, 'NEW REGISTERED') AS BOOK_TITLE, IFNULL(BD.BOOK_COMPANY, 'RENT-A-BOOK') AS COMPANY,BD.RETURN_DATE AS RETURN
FROM BOOK_USER BU
LEFT JOIN (SELECT * FROM (SELECT USR_ID, BOOK_TITLE, BOOK_COMPANY, RETURN_DATE FROM BOOKING_DETAIL ORDER BY RETURN_DATE DESC) AS A GROUP BY USR_ID) AS BD ON (BU.USR_ID = BD.USR_ID)
ORDER BY BU.USR_ID;