By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE userBonuses (
id INT,
userId INT,
bonusId INT
)
CREATE TABLE orders (
id INT,
userId INT
)
INSERT INTO
`orders` (`id`, `userId`)
VALUES
(1, 10),
(2, 10),
(3, 10)
SELECT
`id`,
`userId`
FROM
`orders` AS `bonus_program`
id | userId |
---|---|
1 | 10 |
2 | 10 |
3 | 10 |
CREATE TABLE bonuses (
id INT,
ordersCount INT
)
INSERT INTO
`bonuses` (`id`, `ordersCount`)
VALUES
(1, 1),
(2, 2),
(3, 6)
SELECT `id`, `ordersCount`
FROM `bonuses` AS `bonuses`
id | ordersCount |
---|---|
1 | 1 |
2 | 2 |
3 | 6 |
SELECT
*
FROM
(
SELECT
*
FROM
`bonuses` AS `bonuses`
) AS `bp`
JOIN (
SELECT
`orders`.`userId`,
COUNT(*) AS `order_counts`
FROM
`orders`
GROUP BY
`userId`
) AS `or` ON `or`.`order_counts` > `bp`.`ordersCount`
id | ordersCount | userId | order_counts |
---|---|---|---|
2 | 2 | 10 | 3 |
1 | 1 | 10 | 3 |