问题描述
我有桌子:
1.Workers(id,name)
2.BonusPenalties(id,worker_id,type,value)
3.犯规(id,value)
对于 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”来连接此表,但结果出错
解决方法
如果我将表 2 和表 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 之后。