当我知道记录是唯一的时,会抱怨抱怨违反唯一性

时间:2018-07-10 19:56:39

标签: sql postgresql

我正在处理一个应用程序并添加用户名。到目前为止,我们一直仅依靠电子邮件。

我正在编写一个查询,以根据名字和姓氏生成用户名。运行查询时,在用户名列上收到有关唯一性违规的错误。但是,当检查它抱怨的记录时,我发现它绝对是唯一的。我想念什么?

查询:

WITH u2 AS (SELECT id, ROW_NUMBER() OVER(PARTITION BY first_name, last_name ORDER BY id ASC) AS row, first_name, last_name FROM users)
UPDATE users
  SET username = COALESCE(left(trim(u2.first_name),1), '')||COALESCE(replace(trim(u2.last_name), ' ', '_'), '')||(CASE WHEN u2.row > 1 THEN u2.row::varchar ELSE '' END)
  FROM u2
  WHERE users.id = u2.id;

2 个答案:

答案 0 :(得分:1)

行号应该在username上而不是对(first_name, last_name)上进行计算,因为用户的姓氏和名字都以相同的字母开头,例如:

INSERT INTO users (first_name, last_name) VALUES
    ('John', 'Smith'),
    ('Jerry', 'Smith');

因此查询应如下所示:

WITH u1 AS (
    SELECT
        id,
        COALESCE(left(trim(first_name),1), '') ||
        COALESCE(replace(trim(last_name), ' ', '_'), '') as new_username
    FROM users
    ),
u2 AS (
    SELECT 
        id,
        new_username,
        ROW_NUMBER() OVER(PARTITION BY new_username ORDER BY id) AS row
    FROM u1
    )
UPDATE users u
    SET username = new_username ||
        CASE WHEN u2.row > 1 THEN u2.row::varchar ELSE '' END
    FROM u2
    WHERE u.id = u2.id

答案 1 :(得分:0)

我认为您需要在此更新中的WHERE条件。 (对Postgres语法不确定100%)

WITH u2 AS 
  ( SELECT ROW_NUMBER() OVER
             ( PARTITION BY first_name, last_name 
                   ORDER BY id ASC
             ) AS row, 
           first_name, 
           last_name 
      FROM users
  )
UPDATE users
  SET username = COALESCE(left(trim(u2.first_name),1), '')||COALESCE(replace(trim(u2.last_name), ' ', '_'), '')||(CASE WHEN u2.row > 1 THEN u2.row::varchar ELSE '' END)
  FROM u2
 WHERE first_name = u2.first_name
   AND last_name = u2.last_name;