每个个人ID限制为两个结果

时间:2016-10-12 14:35:54

标签: mysql

我如何为每个人meeting.id返回两个结果?

我尝试了Row_Count()Rank()之类的内容,但它们似乎会导致语法错误。

这是我的查询,我需要根据meeting.id显示两个结果。

    SELECT meeting_appointment.* FROM `meeting` 
    INNER JOIN meeting_appointment ON ( 
        meeting_appointment.meeting_id = meeting.id AND meeting_appointment.pupil_id = 0 AND meeting_appointment.guardian_id = 0 AND meeting_appointment.deleted = 0 
    ) 
    WHERE ( 
        meeting.grade_id = "-1" OR meeting.grade_id IN ('87') 
    ) 
    AND meeting.startTime < '2016-10-06 14:00:00' + INTERVAL 1 HOUR AND meeting.startTime > '2016-10-06 14:00:00' - INTERVAL 1 HOUR

    GROUP by meeting_appointment.id 
    ORDER BY meeting_appointment.startTime ASC

2 个答案:

答案 0 :(得分:1)

您没有聚合函数,因此GROUP BY是多余的。删除它,并添加一个LIMIT子句,你应该好好去:

SELECT ma.*
FROM meeting m
INNER JOIN meeting_appointment ma ON ma.meeting_id = m.id
WHERE m.grade_id IN ('-1','87')
AND ma.pupil_id = 0
AND ma.guardian_id = 0
AND ma.deleted = 0 
AND m.startTime < '2016-10-06 14:00:00' + INTERVAL 1 HOUR
AND m.startTime > '2016-10-06 14:00:00' - INTERVAL 1 HOUR
ORDER BY ma.startTime ASC
LIMIT 2;

您还可以将BETWEEN用于datetime列。

答案 1 :(得分:1)

如果你的meeting_appointment.id是连续的,那么这应该显示前两个 meeting_appointment.id per meeting.id:

SELECT meeting_appointment.* FROM `meeting` 
INNER JOIN meeting_appointment ON (meeting_appointment.meeting_id = meeting.id)

WHERE (meeting.grade_id = "-1" OR meeting.grade_id IN ('87')) 
AND meeting.startTime < '2016-10-06 14:00:00' + INTERVAL 1 HOUR AND meeting.startTime > '2016-10-06 14:00:00' - INTERVAL 1 HOUR
AND meeting_appointment.pupil_id = 0 
AND meeting_appointment.guardian_id = 0 
AND meeting_appointment.deleted = 0 
AND NOT EXISTS 
(SELECT 1 FROM meeting_appointment ma WHERE ma.id<meeting_appointment.id-1
    AND ma.pupil_id = 0 
    AND ma.guardian_id = 0 
    AND ma.deleted = 0
)
GROUP by meeting_appointment.id 
ORDER BY meeting_appointment.startTime ASC 

如果你的meeting_appointment.id只是随机的或非数字的,那么它可能需要一些调整,但为了编码这些柚木,我们需要更多地了解模式。