简体   繁体   中英

Two INSERT INTO statements for the same row SQL/php

I have been trying so hard and I can't find a solution for this problem. I have two different INSERT statements:

INSERT INTO `logList`(`User_ID`) SELECT `User_ID` FROM `userList` WHERE keyname='somevalue';
INSERT INTO `logList`(`ttime`) VALUES (CURRENT_TIMESTAMP);

If I execute them, they will of course insert 2 different rows. How can I make a single INSERT that returns only one row? Thank you in advance.

I am going to assume that this is what you really want:

INSERT INTO logList (User_ID, ttime)
    SELECT User_ID, CURRENT_TIMESTAMP
    FROM userList
    WHERE keyname = 'somevalue';

I doubt you want two separate rows, one with the user and NULL for time and the other with NULL for user and a value of the time.

I should note that you can define the loglist so ttime is defaulted to the current timestamp on the insert. The use of such defaults is described in the documentation .

If you did that, then:

INSERT INTO logList (User_ID)
    SELECT User_ID
    FROM userList
    WHERE keyname = 'somevalue';

would always set ttime .

As you ask, you can do it in one single Insert:

INSERT INTO `logList`(`User_ID`, `ttime`)
    SELECT `User_ID`, CURRENT_TIMESTAMP
    FROM `userList`
    WHERE keyname='somevalue';

You have this command:

INSERT INTO `logList`(`User_ID`) SELECT `User_ID` FROM `userList` WHERE keyname='somevalue';
INSERT INTO `logList`(`ttime`) VALUES (CURRENT_TIMESTAMP);

Which will create two rows and you want to create a single row. You can do that using a single command:

insert into loglist(USER_ID, ttime)
select User_ID, now()
from userList
where keyname = 'somevalue';

However, even though this is a solution, it is not a very elegant one. You should alter loglist and modify ttime to have the default value of CURRENT_TIMESTAMP and then you can simplify your insert command like this:

insert into loglist(USER_ID)
select User_ID
from userList
where keyname = 'somevalue';

this should be the normal behavior, since your loglist table should probably have the timestamp of the insertion moment anyway.

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