我正在使用Java Spring JPA框架,我有下表:
+----+---------+-----------+
| id | userID | creditID |
+----+---------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 4 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
+----+---------+-----------+
我想根据userID
进行查询,以获取最新且唯一的creditIDs
。我最近尝试过查询"SELECT * FROM Table WHERE user_id = 'userId' GROUP BY credit_id"
,因为我的runtime errors
语句,我得到了group by
。
实现以下结果的最简单的语法是什么?
+----+---------+-----------+
| id | userID | creditID |
+----+---------+-----------+
| 3 | 1 | 3 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
+----+---------+-----------+
答案 0 :(得分:1)
您的问题的解决方案
SELECT id, user_id, distinct(creditID) FROM Table WHERE user_id = 1
答案 1 :(得分:1)
使用select
并过滤where
:
select t.*
from t
where t.id = (select max(t2.id) from t t2 where t2.userid = t.userid and t2.creditid = t.creditid) and
t.userid = 1;
答案 2 :(得分:0)
SELECT id, userid, DISTINCT(creditid) FROM table WHERE userid = 'required user id';