我有兩個表。SQL JOIN和第二個表中的一些條件的限制結果
投資組合:
+----+-------+--------------+
| id | name | created_date |
+----+-------+--------------+
| 1 | Port 1| 2017/08/12 |
+----+-------+--------------+
| 2 | Port 2| 2017/08/14 |
+----+-------+--------------+
| 3 | Port 3| 2017/08/15 |
+----+-------+--------------+
照片:
+----+------------+--------------+--------------+-----------------+
| id | Port_name | port_id | user_id | created_at |
+----+------------+--------------+--------------+-----------------+
| 1 | Port 1 | 1 | null | 2017/08/10 |
+----+------------+--------------+--------------+-----------------+
| 2 | Port 2 | 2 | null | 2017/08/11 |
+----+------------+--------------+--------------+-----------------+
| 3 | Port 3 | 3 | null | 2017/08/12 |
+----+------------+--------------+--------------+-----------------+
| 4 | Port 1 | 1 | 1 | 2017/08/13 |
+----+------------+--------------+--------------+-----------------+
| 5 | Port 2 | 2 | 1 | 2017/08/14 |
+----+------------+--------------+--------------+-----------------+
| 6 | Port 3 | 3 | 1 | 2017/08/15 |
+----+------------+--------------+--------------+-----------------+
| 7 | Port 2 | 2 | 1 | 2017/08/16 |
+----+------------+--------------+--------------+-----------------+
| 8 | Port 3 | 3 | 1 | 2017/08/17 |
+----+------------+--------------+--------------+-----------------+
| 9 | Port 2 | 2 | 1 | 2017/08/18 |
+----+------------+--------------+--------------+-----------------+
|10 | Port 3 | 3 | 1 | 2017/08/19 |
+----+------------+--------------+--------------+-----------------+
我怎樣才能查詢得到結果如下圖所示:
結果:
+---------+------------+----------------+-----------------+
| Port_id | port_name | photo_id | photo_created_at|
+---------+------------+----------------+-----------------+
| 2 | Port 2 | 7 | 2017/08/16 |
+---------+------------+----------------+-----------------+
| 3 | Port 3 | 8 | 2017/08/17 |
+---------+------------+----------------+-----------------+
我想要做的是加入投資組合表照片表,並照片表的一些條件限制的結果:
- user_id是不是空
- created_at是「第二古老」。
「第二最老的」 含義是,例如,我有4個日期時間: 2017/08/11
,2017/08/12
,2017/08/16
,2017/08/19
。
在這種情況下,「第二最老」是2017/08/12
。
我已經嘗試過自己:
SELECT p.id as Port_id,
p.name as Port_name,
ph.id as photo_id,
ph.created_at as photo_created_at
FROM "Portfolios" AS p
LEFT JOIN (
SELECT *
FROM "Photos"
WHERE user_id IS NOT NULL
ORDER BY created_at ASC
LIMIT 1 OFFSET 1) as ph
ON p.id = ph.port_id;
,並用Google搜索這一點,但發現沒有解決我的問題。
任何幫助? 感謝您的進步!
出在你的例子這四個日期,怎麼是'2017年/ 08/12'「半最老」?你的意思是「第二古老」? – user2877959
@ user2877959是的,我的意思是「第二古老」。 – javimuu
好的。但我仍然不明白你想要的結果。爲什麼沒有進入組合1?照片#7是投資組合2中第二古老的照片?它不應該是#5嗎?投資組合3同樣適用... – user2877959