Hier is een geldig resultaat voor een eenvoudiger probleem.
- 1 ochtend, 1 middag, 1 avond en 1 nacht 'ploeg'
- som van het 'tarief' <50
- AA en BB (de enige mogelijke waarden) moeten elk twee keer voorkomen
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,code CHAR(2) NOT NULL
,shift VARCHAR(12) NOT NULL
,rate INT NOT NULL
);
INSERT INTO my_table VALUES
( 1 , 'AA' , 'Morning' , 10),
( 2 , 'BB' , 'Afternoon' , 20),
( 3 , 'AA' , 'Evening' , 13),
( 4 , 'BB' , 'Night' , 18),
( 5 , 'BB' , 'Morning' , 15),
( 6 , 'AA' , 'Afternoon' , 25),
( 7 , 'BB' , 'Evening' , 15),
( 8 , 'AA' , 'Night' , 22),
( 9 , 'AA' , 'Morning' , 10),
(10 , 'BB' , 'Afternoon' , 20),
(11 , 'AA' , 'Evening' , 13),
(12 , 'AA' , 'Night' , 18),
(13 , 'BB' , 'Morning' , 15),
(14 , 'BB' , 'Afternoon' , 25),
(15 , 'AA' , 'Evening' , 15),
(16 , 'BB' , 'Night' , 22),
(17 , 'AA' , 'Morning' , 10),
(18 , 'BB' , 'Afternoon' , 20),
(19 , 'BB' , 'Evening' , 13),
(20 , 'AA' , 'Night' , 18),
(21 , 'AA' , 'Morning' , 15),
(22 , 'BB' , 'Afternoon' , 25),
(23 , 'AA' , 'Evening' , 15),
(24 , 'BB' , 'Morning' , 10),
(25 , 'BB' , 'Afternoon' , 2),
(26 , 'AA' , 'Evening' , 8),
(27 , 'BB' , 'Night' , 3),
(28 , 'AA' , 'Morning' , 5),
(29 , 'BB' , 'Afternoon' , 2),
(30 , 'AA' , 'Evening' , 1),
(31 , 'BB' , 'Night' , 2),
(32 , 'AA' , 'Night' , 2);
SELECT * -- for simplicity. In reality, we would need to name and alias all columns for this result to be usable
FROM my_table morning1
JOIN my_table afternoon1
ON afternoon1.id <> morning1.id
JOIN my_table evening1
ON evening1.id NOT IN(morning1.id,afternoon1.id)
JOIN my_table night1
ON night1.id NOT IN(morning1.id,afternoon1.id,evening1.id)
WHERE morning1.shift = 'morning'
AND afternoon1.shift = 'afternoon'
AND evening1.shift = 'evening'
AND night1.shift = 'night'
AND morning1.rate + afternoon1.rate + evening1.rate + night1.rate < 50
AND LENGTH(REPLACE(CONCAT(morning1.code,afternoon1.code,evening1.code,night1.code),'AA',''))=4
ORDER
BY RAND() LIMIT 1;
+----+------+---------+------+----+------+-----------+------+----+------+---------+------+----+------+-------+------+
| id | code | shift | rate | id | code | shift | rate | id | code | shift | rate | id | code | shift | rate |
+----+------+---------+------+----+------+-----------+------+----+------+---------+------+----+------+-------+------+
| 1 | AA | Morning | 10 | 25 | BB | Afternoon | 2 | 15 | AA | Evening | 15 | 27 | BB | Night | 3 |
+----+------+---------+------+----+------+-----------+------+----+------+---------+------+----+------+-------+------+
(Een van de 721 geldige resultaten)