有这个表:
Row Pos Outdata Mismatch Other
1 10 S 0 A
2 10 S 5 A
3 10 R 0 B
4 10 R 7 B
5 20 24 0 A
6 20 24 5 B
6 20 32 10 C
如何选择具有唯一Outdata的Pos = 10的所有行。如果存在多行,我希望字段Mismatch最小的行。即我想获得第1行和第3行,而不是第2行和第4行。
在那个选择中我也想对所有Pos = 20做同样的事情,所以总结果应该是行1,3,5,6
(然后我想访问“其他”字段,所以我不能只在Pos和OutData和Mismatch上选择SELECT DISTINCT)。
在MySQL中是否有查询要执行此操作?
答案 0 :(得分:2)
这里我假设(Pos,OutData,Mismatch)不唯一,但是(Row,Pos,OutData,Mismatch) 唯一:
SELECT T3.*
FROM Codes T3
JOIN (
SELECT MIN(Row) AS Row
FROM (
SELECT Pos, OutData, Min(Mismatch) AS Mismatch
FROM Codes
GROUP BY Pos, OutData
) T1
JOIN Codes T2
ON T1.Pos = T2.Pos AND T2.OutData = T2.Outdata AND T1.Mismatch = T2.Mismatch
GROUP BY T2.Pos, T2.OutData, T2.Mismatch
) T4
ON T3.Row = T4.Row
结果:
1, 10, 'S', 0, 'A'
3, 10, 'R', 0, 'B'
5, 20, '24', 0, 'A'
7, 20, '32', 10, 'C'
请注意,我已将第二行6更正为第7行,因为我认为这是一个错误。
答案 1 :(得分:1)
试试这个:
Select * From Table ot
Where pos = 10
And MisMatch =
(Select Min(MisMatch) From Table
Where pos = 10
And Outdata = ot.OutData)
答案 2 :(得分:1)
基本原理是创建一个包含Pos,OutData和最低不匹配值的表格,并将这些字段的组合用作实际表格中的唯一键。
SELECT t1.*
FROM MyTable t1
INNER JOIN (
SELECT Pos, OutData, Mismatch = MIN(Mismatch)
FROM MyTable
GROUP BY Pos, OutData
) t2 ON t2.Pos = t1.Pos
AND t2.OutData = t1.OutData
AND t2.Mismatch = t1.Mismatch
答案 3 :(得分:0)
这应该适合你:
SELECT *
FROM table T1
GROUP BY Pos, Outdata
HAVING Mismatch = (
SELECT MIN(Mismatch)
FROM table T2
WHERE Pos = T1.Pos AND
Outdata = T1.Outdata
)