58

嘿,我想弄清楚如何使用以下查询插入新记录:

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桌子

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);
4

3 回答 3

77

您必须具体说明您选择的列。如果您的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 不支持同时插入多个表。您需要在代码中执行两条语句,使用第一个查询中的最后一个插入 ID,或者在主表上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
于 2012-08-22T12:50:05.217 回答
24

使用另一个查询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
);
于 2012-08-22T12:50:22.647 回答
3
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
)
于 2019-04-20T05:58:04.307 回答