MySQL 多个 "left join" 和 "having"

MySQL multiple "left join" and "having"

我有桌子:

1.Workers(id,姓名)

2.BonusPenalties(id,worker_id,类型,worker_id,值)

3.Fouls(id,worker_id,值)

对于 BonusPenalties 列,“type”可以是“0”或“1”,其中 0 - 是奖金,1 - 是罚款

所以我需要能够按奖金/处罚/犯规的数量过滤工人

类似于where count(BonusPenalties.id) > 5(for penalties) and count(BonusPenalties.id) >7(for bonuses) and count(Fouls.id) < 100

我尝试通过左连接并使用“HAVING”连接此表,但结果出错

write the example for joining if I will combine tables 2 and 3

CREATE TABLE effects (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    worker_id INT NOT NULL,
    FOREIGN KEY fk_worker_id REFERENCES worker (worker_id),
    type ENUM('bonus', 'penalty', 'foul') NOT NULL,
    value DECIMAL(10, 2) NOT NULL DEFAULT 0
);

现在没有连接乘法,你可以使用类似的东西

HAVING SUM(type='bonus') > 2
   AND SUM(type='foul') = 0

HAVING SUM(type='bonus') > 2 -- check bonuses amount
   AND SUM(CASE WHEN type='foul' THEN value ELSE 0 END) < 1000 -- check total sum of fouls

在 GROUP BY 之后。