Insert using LEFT JOIN and INNER JOIN

后端 未结 3 1069
南旧
南旧 2020-12-07 19:02

Hey all i am trying to figure out how to go about inserting a new record using the following query:

SELECT user.id, user.name, user.username, user.email, 
           


        
相关标签:
3条回答
  • 2020-12-07 19:15

    You have to be specific about the columns you are selecting. If your user table had four columns id, name, username, opted_in you must select exactly those four columns from the query. The syntax looks like:

    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
    

    However, there does not appear to be any reason to join against user_permission here, since none of the columns from that table would be inserted into user. In fact, this INSERT seems bound to fail with primary key uniqueness violations.

    MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT statements in your code, using the last insert id from the first query, or create an AFTER INSERT trigger on the primary table.

    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)
    

    Or using a trigger:

    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
    
    0 讨论(0)
  • 2020-12-07 19:25
    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
    )
    
    0 讨论(0)
  • 2020-12-07 19:34

    you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

    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
    );
    
    0 讨论(0)
提交回复
热议问题