【问题标题】:Can I create an email for the user based on input for the first and last name using postgreSQL?我可以使用 postgreSQL 根据输入的名字和姓氏为用户创建电子邮件吗?
【发布时间】:2021-04-05 15:45:20
【问题描述】:

我是 Postgres 的新手,我正在制作一个模拟数据库来管理大学的学生,以便更好地了解 Postgres 的工作原理。

我正在创建一个学生表,其中包含学生 ID、入学日期、毕业年份、名字/姓氏和大学电子邮件地址的列。目前我只是将电子邮件列设置为 NOT NULL 并且用户必须输入他们自己的电子邮件地址,但显然这不是大学电子邮件地址的工作方式。

我想知道是否有一种方法可以根据用户输入的名字和姓氏来动态创建电子邮件。例如,如果我要运行以下查询:

INSERT INTO students (first_name, last_name) VALUES ('bob', 'smith');

将为 bob smith 动态创建一个电子邮件地址,格式为“bobsmith@university.com”,因此我的表格如下所示:

 student_id | enrollment_date | grad_year |             email              | student_first | student_last 
------------+-----------------+-----------+--------------------------------+---------------+--------------
          2 | 2020-12-28      |    2024   |     bobsmith@university.com    |      bob      | smith

有没有一种方法可以创建一个函数,该函数从 student_first 和 student_last 列中获取值并根据它们创建电子邮件?

任何指向可读文档的链接都会很有用。

【问题讨论】:

    标签: sql postgresql sql-insert calculated-columns create-table


    【解决方案1】:

    有几种方法可以实现你想要的:一个函数/过程或一个(我讨厌说)一个 Trugger。但是,在这种情况下,生成的列将不起作用:当第二个学生“Bob Smith”注册时会发生什么。您可以使用函数来生成电子邮件地址 - 如果需要,可以使用数字使其唯一。

    create or replace 
    function generate_email_address(first_name_in text
                                   ,last_name_in  text
                                   )
      returns text 
      language sql 
    as $$
       with email(num) as 
            ( select count(*) 
                from students 
               where lower(first_name) = lower(first_name_in) 
                 and lower(last_name)  = lower(last_name_in) 
            ) 
       select lower(first_name_in) ||
              lower(last_name_in)  || 
              case when num = 0 then '' else to_char(num+1,'FM99') end ||
              '@university.com'
         from email; 
    $$; 
    

    example:

    【讨论】:

    • 你知道有没有一种方法我只能在重复的情况下添加数字,而不是在第一个条目上?
    • 检查上面答案中的示例。这正是它的作用。
    【解决方案2】:

    将以“bobsmith@university.com”格式为 bob smith 即时创建电子邮件地址

    您可以使用generated column

    create table students (
        student_id serial primary key,
        first_name text not null,
        last_name text not null,
        ...
        email text 
            generated always as (first_name || '.' || last_name || '@university.com') 
            stored
    );
    

    Demo on DB Fiddle

    INSERT INTO students (first_name, last_name) VALUES ('bob', 'smith');
    -- 1 rows affected
    
    SELECT * FROM students;
    
    student_id | first_name | last_name | email                   
    ---------: | :--------- | :-------- | :-----------------------
             1 | bob        | smith     | bob.smith@university.com
    

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2017-03-05
      • 1970-01-01
      • 2021-12-06
      • 2020-04-17
      相关资源
      最近更新 更多