我有一个表,包含两列A和B具有唯一值约束。当用户在数据库中输入新值A1和B1时,我想检查A1不存在于A列中,B1也不存在于B列中。
- 编辑
这两个列在数据库中已经是唯一的。我想编写一个查询来搜索给定的值,如果返回值为 null,那么用户可以添加新值A1和B1。如果有匹配,那么我会给用户消息,他不能添加这些值。
我有一个表,包含两列A和B具有唯一值约束。当用户在数据库中输入新值A1和B1时,我想检查A1不存在于A列中,B1也不存在于B列中。
- 编辑
这两个列在数据库中已经是唯一的。我想编写一个查询来搜索给定的值,如果返回值为 null,那么用户可以添加新值A1和B1。如果有匹配,那么我会给用户消息,他不能添加这些值。
Which of there do you want?
Each option requires a unique constraint (or index) on
All SQL dialects allow you to set multiple columns in constraints
Classic SQL would be this. I assume A and B are varchar here
INSERT mytable (A, B)
SELECT 'A1', 'B1'
WHERE NOT EXISTS (SELECT * FROM mytable WHERE A= 'A1' AND B = 'B1')
This is not safe for concurrency, so there are nicer options
Also, note, you don't usually test first, report to user, allow write. There is no guarantee that the values could be written between SELECT and later INSERT.