Sql:为一列的一个值设置distinct

时间:2014-10-08 16:28:47

标签: mysql sql unique distinct

是否可以设置它,以便如果您尝试创建一个表格,其中两个值匹配,一个值是特定值,例如1,那么它不会让您?

我想要一张这样的表:

Table1_id: | Table1_name:
1          | Edgar
2          | Rudy

Table2_id: | Table2_Table1_id |Table2_active(bit):
1          | 1                | 1 (this is okay)
2          | 1                | 0 (this is okay)
3          | 1                | 1 (this is NOT okay) // shouldn't work
4          | 1                | 0 (this is still okay)
5          | 2                | 1 (this is okay)
6          | 2                | 0 (this is okay)
7          | 2                | 1 (this is NOT okay) // shouldn't work
8          | 2                | 0 (this is still okay)

我希望能够拥有尽可能多的(x,0s),但只能拥有一个(x,1) 怎么能实现呢?

编辑:可能的解决方案:

CREATE TRIGGER active_check BEFORE INSERT ON table2`
IF EXISTS (SELECT table2_id FROM table_2 WHERE table2_table1_id = NEW.table2_table1_id WHERE active = 1)
BEGIN
ROLLBACK TRANSACTION;
RETURN
END;

即使它在自己的陈述中,我对New.table2_table1_id的使用是否会在这里工作?如果不是,我怎么能绕过那个?

0 个答案:

没有答案