大家好,我在显示查询代码中的数据时遇到问题。 我想显示今天最近日期的数据。下面是我的示例数据和我要显示的输出数据。
Landing Area data
|landing_id| id_number| address |
---------------------------------
| 1 | 00012345 | Ozamiz |
| 2 | 00012346 | Tudela |
| 3 | 00012347 | Nailon |
| 4 | 00012348 | Taboo |
| 5 | 00012349 | Jimenez |
| 6 | 00012350 | Tangub |
---------------------------------
Percentage data
|percent_id| landing_id | percentage | date_added |
-----------------------------------------------------------
| 1 | 1 | 9 |2018-10-08 21:42:22 |
| 2 | 1 | 12 |2018-10-03 20:43:32 |
| 3 | 1 | 43 |2018-10-15 19:43:49 |
| 4 | 3 | 22 |2018-10-10 15:43:56 |
| 5 | 3 | 77 |2018-10-12 18:44:03 |
-----------------------------------------------------------
这是我的查询代码。
SELECT fish_landing.landing_id,
percentage.landing_id as percentage_landing_id,
percentage.percentage,
percentage.date_added
FROM percentage
RIGHT OUTER JOIN fish_landing ON percentage.landing_id = fish_landing.landing_id
ORDER BY fish_landing.landing_id ASC
我的代码的输出是这样的,其中date_added和百分比不准确。
|percent_id| percentage | date_added |
----------------------------------------------
| 1 | 9 |2018-10-08 21:42:22 |
| 2 | | |
| 3 | 22 |2018-10-10 15:43:56 |
| 4 | | |
| 5 | | |
| 6 | | |
----------------------------------------------
我要显示的输出数据是下表,其中将显示每个landing_id中具有最新date_added的百分比。
|landing_id| percentage | date_added | address |
--------------------------------------------------------
| 1 | 43 |2018-10-15 19:43:49 | Ozamiz |
| 2 | | | |
| 3 | 77 |2018-10-12 18:44:03 | Nailon |
| 4 | | | |
| 5 | | | |
| 6 | | | |
--------------------------------------------------------
我希望你能帮助我解决我的问题。
您可以在单独的派生表中获取landing_id的最大date_added,并将其用于连接。
请尝试以下操作:
SELECT fish_landing.landing_id,
percentage.percentage,
percentage.date_added,
fish_landing.address
FROM fish_landing
LEFT JOIN percentage ON percentage.landing_id = fish_landing.landing_id
LEFT JOIN (SELECT landing_id, MAX(date_added) AS max_date_added
FROM percentage
GROUP BY landing_id) AS dt
ON dt.landing_id = percentage.landing_id AND
dt.max_date_added = percentage.date_added
ORDER BY fish_landing.landing_id ASC