简体   繁体   中英

sql insert query with select

Given this table where both reviewid and prankid are auto increment.

CREATE TABLE Review
(
reviewId INT NOT NULL AUTO_INCREMENT,
email VARCHAR(32) NOT NULL,
prankId INT NOT NULL,
rating INT,
comment VARCHAR(1056) NOT NULL,
PRIMARY KEY(reviewId),
FOREIGN KEY (email) REFERENCES User(email),
FOREIGN KEY (prankId) REFERENCES Prank(prankId)
);

Would this insert statement correctly insert values into all of the attributes in review table.

INSERT INTO Review (email, prankId) SELECT email, prankId from User;
INSERT INTO Review (rating, comment) VALUES(‘5’,’amazing!’);
INSERT INTO Review (rating, comment) VALUES(‘5’,’brilliant!’);

I suspect that you want this:

INSERT INTO Review (email, prankId, rating, comment)
    SELECT email, prankId, 'S', 'amazing!'
    from User;

INSERT INTO Review (email, prankId, rating, comment)
    SELECT email, prankId, 'S', 'brilliant'
    from User;

In your version, the last two insert s will fail because email and prankid are NULL . Remember, insert adds new rows into the table. It doesn't modify existing rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM