使用左连接和内连接插入

qv7cva1a  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(259)

嘿,我想知道如何使用以下查询插入新记录:

SELECT user.id, user.name, user.username, user.email, 
  IF(user.opted_in = 0, 'NO', 'YES') AS optedIn  
FROM 
  user
  LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
ORDER BY user.id;

我的 INSERT 目前为止的问题是:

INSERT INTO user 
SELECT * 
FROM user 
  LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id;

但是,我不知道该怎么办 VALUE('','','','', etc etc) 使用左连接和内连接时。
所以我要做的是: User 表格:

id    | name       | username    | password                 | OptIn
--------------------------------------------------------------------
562     Bob Barker   bBarker       BBarker@priceisright.com   1

还有 user_permission table

user_id   | Permission_id
-------------------------
562         4

这么说?

INSERT INTO user (name, username, password, email, opted_in) VALUES ('Bbarker','Bbarker','blahblahblah','Bbarker@priceisright.com',0);
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(),4);
gr8qqesn

gr8qqesn1#

你必须明确你选择的列。如果你的 user 表有四列 id, name, username, opted_in 您必须从查询中恰好选择这四列。语法如下所示:

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

然而,似乎没有任何理由加入反对的行列 user_permission 这里,因为该表中的所有列都不会插入到 user . 事实上,这个 INSERT 主键唯一性冲突似乎注定会失败。
mysql不支持同时插入多个表。你要么做两个 INSERT 语句,或者创建 AFTER INSERT 主表上的触发器。

INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)

或者使用触发器:

CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
  INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END
cgyqldqp

cgyqldqp2#

INSERT INTO Test([col1],[col2]) (
    SELECT 
        a.Name AS [col1],
        b.sub AS [col2] 
    FROM IdTable b 
    INNER JOIN Nametable a ON b.no = a.no
)
sh7euo9m

sh7euo9m3#

你不能使用 VALUES 使用另一个 SELECT 查询。请参见插入语法

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

相关问题