mysql返回两个带限制的最小值

时间:2017-03-11 10:30:08

标签: mysql

我有一个名为:workers的表和一个名为:schedule的表,格式如下:

工人:

| id | name      | vacationA  | vacationB  | workhistory |
|  1 | Florin    | 2017-05-05 | 2017-05-25 | 2010-01-01  |
|  2 | Andrei    | 2017-06-05 | 2017-06-25 | 2010-01-01  |
|  3 | Alexandra | 2017-07-05 | 2017-07-25 | 2010-01-01  |
|  4 | Emilia    | 2017-08-05 | 2017-08-25 | 2010-01-01  |
|  5 | Nicoleta  | 2017-09-05 | 2017-09-25 | 2010-01-01  |
+----+-----------+------------+------------+-------------+

时间表:

| day | month | name      | shifts |
+-----+-------+-----------+--------+
|   1 |     6 | Florin    |      0 |
|   1 |     6 | Andrei    |      1 |
|   1 |     6 | Alexandra |      2 |
|   1 |     6 | Emilia    |      3 |
|   1 |     6 | Nicoleta  |      4 |
+-----+-------+-----------+--------+

我需要查询表格"工人"给我2个随机名称,最小班次数,工人不应该在休假期间。工作历史也必须大于18个月。 在这种情况下,我需要的查询应该返回Florin和Andrei。

这是我到目前为止所得到的,但它并没有像预期的那样工作:

SELECT name
FROM workers
WHERE (CURDATE() NOT BETWEEN vacationA AND vacationB) AND
      workhistory > (DATE_SUB(CURDATE(), INTERVAL 18 MONTH)) AND
      name IN (SELECT name FROM schedule ORDER BY shifts LIMIT 2)
ORDER BY RAND() LIMIT 2;

此查询返回 1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

谢谢!

1 个答案:

答案 0 :(得分:0)

加入schedule,然后使用LIMIT 2

SELECT w.name
FROM workers w
INNER JOIN schedule s
    ON w.name = s.name
WHERE CURDATE() NOT BETWEEN w.vacationA AND w.vacationB AND
      w.workhistory > DATE_SUB(CURDATE(), INTERVAL 18 MONTH)
ORDER BY s.shifts
LIMIT 2;

我不理解随机排序,因为你只返回两个工人记录,而这些记录不是随机选择的,而是属于最小的班次数。