我有一个名为auction的表,它有各种列,如用户名,拍卖ID(主键),名字,姓氏,位置等,以及类别列。默认情况下,类别列为空,除非用户填写特定记录。
我制作了一个新用户表,其中包含用户名和类别列,以及将通过用户输入完成的附加字段。
我想知道在拍卖表中更新记录时是否有可能有一个类别,只要表中没有用户名,就可以将该记录中的用户名和类别插入到用户表中
例如,如果我有以下表格:
auctions
auctionid username firstname lastname category
------------------------------------------------------------------------
1 zerocool john henry
2 fredflint fred smith
3 azazal mike cutter
然后,在更新第二条记录时,有一个像这样的类别:
2 fredflintsoner fred smith shoes
生成的用户表应为:
users
username shoes pants belts misc1 misc2
--------------------------------------------------
fredflint true
以前没有记录。
如果拍卖表中存在具有相同用户名的其他拍卖,例如:
7 fredflint fred smith belts
然后即使将此拍卖添加到类别中,也不应为用户表插入新记录,因为用户名已经存在,但是应该根据需要进行更新,从而导致:
username shoes pants belts misc1 misc2
--------------------------------------------------
fredflint true true
答案 0 :(得分:2)
您要找的是TRIGGER
。您可以在拍卖表中的每次插入/更新后指定要运行的内容,然后确定对users表执行的操作。
答案 1 :(得分:1)
我想到了几个问题。首先,您的用户表看起来是非规范化的。添加新类别后会发生什么?考虑以下形式的用户表:
id username category
如果用户有多个类别,则您有多行:
1 fredflint shoes
2 fredflint pants
....
我的第二个问题是,为什么你需要一个用户表?看起来用户表中的所有信息都已存储在拍卖表中!您只需通过以下方式检索用户表:
select distinct username, category
from auctions
如果您需要单独的表格,则可以选择在创建新拍卖时手动更新表格。我这样做(我知道足够的触发器来避免它们):
1 - 确保此用户有一行
if not exists (select * from users where username = 'fredflint')
insert into users (username) values ('fredflint')
2 - 确保他是鞋类
if not exists (select * from users where username = 'fredflint' and shoes = 1)
update users set shoes = 1 where username = 'fredflint'