我有一个表'wordstyped',其中包含'idBook','guidUser','bookmarkLetter','letter','attemptWrong'和'isCorrect'。
idBook guidUser bookmarkLetter letter attemptWrong isCorrect
-------------------------------------------------------------------
1 1 100 a 2 0
1 1 100 a 3 0
1 1 100 a 3 1
1 1 101 b 6 0
1 1 101 b 2 0
2 2 101 b 3 0
2 3 152 d 7 0
3 3 153 e 2 0
我想选择所有记录,它们的所有字段都包含最大数量的“ attemptWrong”,但三元组分别为“ idBook”,“ guidUser”和“ bookmarkLetter”。 我已经通过此查询完成了
SELECT DISTINCT w1.bookmarkletter, w1.attemptsWrong
FROM wordstyped w1 INNER JOIN ( SELECT bookmarkLetter, guidUser, idBook,
MAX(attemptsWrong) AS maxAttemptsWrong
FROM wordstyped
GROUP BY bookmarkLetter, guidUser, idBook ) w2
ON w1.bookmarkLetter = w2.bookmarkLetter AND w1.guidUser = w2.guidUser
AND w1.guidUser = '1'
AND w1.idBook ='1'
AND w1.attemptsWrong = w2.maxAttemptsWrong AND w1.bookmarkLetter >=0
AND w1.bookmarkLetter <=200 ORDER BY `w1`.`bookmarkletter` ASC
就像这个小提琴http://sqlfiddle.com/#!9/238794/2
现在,我也要选择'isCorrect',如果至少一个记录的ha值为isCorrect = 1,则选择值为1;如果所有记录的值为0,则选择0。
在示例情况下,如果我将w1.isCorrect添加到第一个select语句 喜欢
SELECT DISTINCT w1.bookmarkletter, w1.attemptsWrong, w1.isCorrect
FROM wordstyped w1 INNER JOIN ( SELECT bookmarkLetter, guidUser, idBook,
MAX(attemptsWrong) AS maxAttemptsWrong
FROM wordstyped
GROUP BY bookmarkLetter, guidUser, idBook ) w2
ON w1.bookmarkLetter = w2.bookmarkLetter AND w1.guidUser = w2.guidUser
AND w1.guidUser = '1'
AND w1.idBook ='1'
AND w1.attemptsWrong = w2.maxAttemptsWrong AND w1.bookmarkLetter >=0
AND w1.bookmarkLetter <=200 ORDER BY `w1`.`bookmarkletter` ASC
(http://sqlfiddle.com/#!9/238794/1),这组记录
idBook guidUser bookmarkLetter letter attemptWrong isCorrect
-------------------------------------------------------------------
1 1 101 b 6 0
1 1 101 b 2 0
2 2 101 b 3 0
正确返回
bookmarkLetter attemptWrong isCorrect
-------------------------------------------------------------------
101 6 0
这组记录
idBook guidUser bookmarkLetter letter attemptWrong isCorrect
-------------------------------------------------------------------
1 1 100 a 2 0
1 1 100 a 3 0
1 1 100 a 3 1
返回
bookmarkLetter attemptWrong isCorrect
-------------------------------------------------------------------
100 3 0
100 3 1
代替
bookmarkLetter attemptWrong isCorrect
-------------------------------------------------------------------
100 3 1
如何获得第二个结果?
编辑:我有isCorrect 1的情况总是像示例中一样发生,即我有两条带有tryWrong的记录是最大值,一个有isCorrect = 0的记录和一个具有isCorrect = 1的记录
答案 0 :(得分:1)
尝试使用汇总和分组依据
http://sqlfiddle.com/#!9/238794/4
SELECT w1.bookmarkletter, max(w1.attemptsWrong), max(w1.isCorrect)
FROM wordstyped w1 INNER JOIN
( SELECT bookmarkLetter, guidUser, idBook, MAX(attemptsWrong) AS maxAttemptsWrong
FROM wordstyped
GROUP BY bookmarkLetter, guidUser, idBook ) w2
ON w1.bookmarkLetter = w2.bookmarkLetter AND w1.guidUser = w2.guidUser
AND w1.guidUser = '1'
AND w1.idBook ='1'
AND w1.attemptsWrong = w2.maxAttemptsWrong AND w1.bookmarkLetter >=0
AND w1.bookmarkLetter <=200
group by w1.bookmarkletter
ORDER BY `w1`.`bookmarkletter` ASC