1

我有一个表,包含两列AB具有唯一值约束。当用户在数据库中输入新值A1B1时,我想检查A1不存在于A列中,B1也不存在于B列中。

- 编辑

这两个列在数据库中已经是唯一的。我想编写一个查询来搜索给定的值,如果返回值为 null,那么用户可以添加新值A1B1。如果有匹配,那么我会给用户消息,他不能添加这些值。

4

1 回答 1

1

Which of there do you want?

  1. A unique independently of other columns
  2. B unique independently of other columns
  3. A and B pairs unique independently of other columns

Each option requires a unique constraint (or index) on

  1. A
  2. B
  3. Both (A,B)

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.

于 2013-05-20T13:16:33.797 回答