0

我有三张桌子:

用户: id、姓名
班次: id、date_start、date_end
users_shifts: user_id、shift_id

我想获取在特定日期范围内完成n 班次的所有用户,其中 n 可以是任何整数(也可以是 0!)。

我可以让所有用户了解他们完成的班次数量,如下所示:

SELECT 
    users.*,
    COUNT(users_shifts.user_id) AS nr_shifts
FROM 
    users
LEFT JOIN 
    users_shifts ON users.id = users_shifts.user_id
GROUP BY 
    users.id

我不知道如何:
1)将日期范围添加到此查询
2)将结果限制为特定的 nr_shifts

任何帮助是极大的赞赏。

4

2 回答 2

0

A second join doesn't do what you need?

SELECT 
    users.*,
    COUNT(users_shifts.user_id) AS nr_shifts
FROM 
    users
LEFT JOIN 
    users_shifts ON users.id = users_shifts.user_id
LEFT JOIN
    shifts ON shifts.id = users_shifts.shift_id
WHERE
    shifts.date_start BETWEEN 2013-06-01 and 2013-06-30
    OR ISNULL(shifts.date_start)
GROUP BY 
    users.id
于 2013-07-03T11:55:09.900 回答
0
SELECT 
users.*,
COUNT(users_shifts.user_id) AS nr_shifts
FROM 
users
LEFT JOIN 
users_shifts ON users.id = users_shifts.user_id
WHERE shifts.date_end = '10/OCT/2012'
GROUP BY 
users.id
Order by users.id
LIMIT 10
于 2013-07-03T11:54:02.397 回答