如何将RowID放入INSERT INTO语句中

问题描述 投票:1回答:1

我有两张桌子 virtual_domains virtual_users。

virtual_domains有一个我的电子邮件服务器的有效域列表,示例数据:

    ID         Name
    1          example.org
    2          example.com
    3          example.net
    
virtual_users keeps the valid email addresses for each domain, and links them to the domain which they belong, example data:
    id         domain_id          password           email address
    1          1                 some               [email protected]
    2          1                 thing              [email protected]
    3          3                 goes               [email protected]
    4          2                 here               [email protected]
    
So to insert a new user, I use this syntax (auto_increment is in use for the id column):
INSERT INTO databasename.virtual_users (
    id, 
    domain_id, 
    password, 
    email ) 
    VALUES (
    DEFAULT, 
    '3', 
    MD5('somepassword'), 
    '[email protected]');
    
and that will add [email protected] to the 5th row as an email user.

我想要做的是,不是为域ID添加'3',而是在那里添加一些其他语法以从相关域的virtual_domains表中返回id,即:

INSERT INTO `databasename`.`virtual_users` ( 
`id`, 
`domain_id`, 
`password`, 
`email` ) 
VALUES (
DEFAULT, 
*ADD_QUERY_HERE_TO_GET_DOMIAN_ID_VALUE_FROM_virtual_domains_TABLE*, 
MD5('somepassword'), 
'[email protected]' );

这样它就可以在一个命令中完成,而不必在单独的查询中查找domain_id。

sql
1个回答
1
投票

您可以在INSERT语句中使用子查询。

 INSERT INTO databasename.virtual_users (
     id, 
     domain_id, 
     password, 
     email
 ) 
     VALUES (
     DEFAULT, 
     ( SELECT ID FROM databasename.virtual_domains WHERE Name = 'example.net' ), 
     MD5('somepassword'), 
     '[email protected]'
 );

我只在SQL Server中对此进行了测试,但我认为它应该适用于大多数数据库。

© www.soinside.com 2019 - 2024. All rights reserved.