So, I have 2 tables: words and wordslearned
I'm working on a project where you can learn some new vocabulary (as a child) and I would like to get: all the words in which the letter is the same as the last word learned by the user. I don't know if it's clear but it's something like: I learn the words
I want to get the all the words in which the initial letter is the same as blue, because it was the last word learned by the user.
The code I wrote is this:
select *
from words p
where letter = (
select letter
from words p
where exists (
select max(idWord)
from wordslearned pa
where p.idWord = pa.idWord and pa.idUser = idUser
)
order by idWord desc
limit 1
)
But with this code, it is showing me words that the user still didn't learn, starting from the bottom because of the "desc".
Could someone help me? If you didn't understand something please tell so I can clarify to you.
EXISTS
just checks whether the subquery finds any rows, the value that it selects is not used. So MAX(idWord)
isn't being used for anything.
You want to get the letter from the last row learned by the user, which is just:
SELECT letter
FROM wordsLearned pa
ORDER BY idWord DESC
WHERE pa.idUser = p.idUser
LIMIT 1
The whole query will then be:
SELECT *
FROM words p
WHERE letter = (
SELECT letter
FROM wordsLearned pa
WHERE pa.idUser = p.idUser
ORDER BY idWord DESC
LIMIT 1
)
This can also be written as a JOIN:
SELECT p.*
FROM words p
JOIN wordsLearned p1 ON p.letter = p1.letter AND p.idUser = p1.idUser
JOIN (
SELECT idUser, MAX(idWord) AS maxId
FROM wordsLearned
GROUP BY idUser) p2 ON p1.idUser = p2.idUser and p1.idWord = p2.maxId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.