来自group by的查询的单个结果

时间:2012-02-11 19:31:53

标签: mysql select

请帮我写这个查询。

我希望得到给定用户最后一次重复的所有单词的日期早于今天或者没有重复。

我有类似的东西,但这是不正确的。

SELECT * FROM `Word` w LEFT JOIN (
    SELECT * FROM `Repetition`
    GROUP BY word_id
    ORDER BY next DESC
) r ON w.id = r.word_id 
WHERE wordset_id = 1 AND (r.user_id IS NULL) OR r.next < CURRENT_DATE

“子查询”应返回给定用户/单词组合的最后重复表

我想得到:所有没有任何重复或具有到期(意味着更早或今天)重复的词(对于给定用户而言)

3 个答案:

答案 0 :(得分:0)

我可能不完全理解这个问题,但是换句话说,你想要返回今天没有重复的所有单词吗?

SELECT * FROM word
WHERE word_id NOT IN (
   SELECT word_id FROM repetition WHERE next >= CURRENT_DATE
)

那样的东西还是我离开了?不确定你在用wordset_id或user_id尝试做什么。

答案 1 :(得分:0)

SELECT * FROM `Word` w LEFT JOIN 
(SELECT word_id, user_id, `repNo`, `repCount`, `date`, `ef`,  MAX(next) next 
 FROM `Repetition` GROUP BY `word_id`,`user_id`) r ON w.id = r.word_id 
WHERE wordset_id = 1 AND (r.user_id IS NULL) OR r.next < CURRENT_DATE

答案 2 :(得分:0)

我认为你不必在这里使用子查询,只要加入你就可以了;

SELECT words.*
FROM words
-- Left join makes sure that you get one result for each word
LEFT JOIN Repetition ON (
    (Words.id = Repetition.word_id)
    -- Get just one user's result
    AND (Repetition.user_id = ?)
)
-- And filter today's results:
WHERE (Repetition.id IS NULL) OR (Repetition.next < NOW())
GROUP BY Words.id