编辑:根据@MostyMostacho在下面的评论中,使用纯SQL无法做到这一点。我会保持打开问题,以防它对其他人有用。
我有这张桌子:
+---+---+
| a | b |
+---+---+
| 1 | J |
+---+---+
| 4 | A |
+---+---+
| 1 | A |
+---+---+
| 6 | A |
+---+---+
| 7 | A |
+---+---+
| 3 | A |
+---+---+
| 5 | A |
+---+---+
| 3 | P |
+---+---+
| 4 | P |
+---+---+
| 1 | P |
+---+---+
| 5 | P |
+---+---+
| 6 | P |
+---+---+
| 7 | P |
+---+---+
我想要这个结果:
+---+---+
| a | b |
+---+---+
| 1 | J |
+---+---+
| 4 | A |
+---+---+
| 6 | A |
+---+---+
| 7 | A |
+---+---+
| 3 | A |
+---+---+
| 5 | A |
+---+---+
我希望第一次出现a
并丢弃后续行。
我应该执行哪些查询才能获得该查询?我的SQL技能正在生锈......
答案 0 :(得分:1)
试试这个:
SELECT T1.*
FROM myTable T1
WHERE NOT EXISTS(
SELECT 'NEXT'
FROM myTable T2
WHERE T2.a = T1.a
AND T2.b > T1.a
)
不存在子查询只获取最后一个,我假设您的订单受到B列ASC值的限制
答案 1 :(得分:0)
如果没有特定的时间戳或以其他方式单调增加id列,则无法查询表中行的插入顺序;数据库引擎可以随意返回任意顺序的行,这可能不是行进入的顺序。
因此,对于大多数使用您提供的表架构的RDBMS,您的建议实际上不可能。
但是你有下表:
+-------+-------+-------+ | id | A | B | +-------+-------+-------+ | 1 | 1 | z | | 2 | 1 | y | | 3 | 1 | x | | 4 | 2 | y | | 5 | 2 | x | | 6 | 3 | x | +-------+-------+-------+
你可以这样做:
SELECT a.A, a.B
FROM Table1 a
INNER JOIN (
SELECT MIN(id) id
FROM Table1
GROUP BY A
) b ON b.id = a.id
答案 2 :(得分:0)
SELECT a.A, a.B
FROM (select @rownum:=@rownum+1 as id, a, b FROM table, (SELECT @rownum:=0) r ) a
INNER JOIN (
SELECT MIN(id) id
FROM (select @rownum:=@rownum+1 as id, a, b FROM table, (SELECT @rownum:=0) r )
GROUP BY A
) b ON b.id = a.id