我有兩個表:嵌套查詢,子查詢SQL
select * from friends;
user_id | friend_id | created_at
---------+-----------+----------------------------
user | user2 | 2017-01-09 21:29:56.31972
user | user3 | 2017-01-09 21:29:58.567925
user | user4 | 2017-01-09 21:30:01.200806
user2 | user | 2017-01-09 21:30:49.498912
user3 | user | 2017-01-09 21:30:53.549042
user4 | user | 2017-01-09 21:30:56.519135
id | user_id | user_from | message
----+---------+-----------+---------
1 | user | user2 | hey
2 | user | user3 | de
3 | user | user4 | bal
4 | user | user3 | ok
5 | user | user3 | nice
6 | user | user4 | cana
7 | user | user2 | doc
此SQL語句成功地檢索的最後一條消息給一個用戶。例如。通過用戶3發送到用戶
select id, user_from, message
from messages
WHERE user_id = 'user'
AND user_from = 'user3'
ORDER BY id DESC
limit 1;
id | user_from | message
----+---------+---------
5 | user3 | nice
的最後一條消息我需要檢索信息的集合。每個消息表示由朋友發送到用戶的最後一條消息
我需要的是通過標準化數據庫,關係數據庫的查詢,使我得到這樣的
id | user_from | message
----+-----------+---------
7 | user2 | doc
5 | user3 | nice
6 | user4 | cana
這不起作用:ERROR:SELECT DISTINCT ON表達式必須初始ORDER BY表達式 LINE 1匹配:SELECT DISTINCT ON(user_from)ID,user_from,消息 – user1000622
我修改與下面的查詢選擇... DISTINCT ON(user_from)id,user_from,來自消息的消息 WHERE user_id ='user'AND user_from ='user3' ORDER BY user_from,id DESC; id | user_from |消息 ---- + ----------- + --------- 5 | user3 |不錯 – user1000622
但仍然沒有達到我想要的。僅檢索一行 – user1000622