简体   繁体   English

同一行SQL / php的两个INSERT INTO语句

[英]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语句:

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. 如果我执行它们,它们当然会插入2个不同的行。 How can I make a single INSERT that returns only one row? 如何制作仅返回一行的单个INSERT 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. 我怀疑您是否需要两行,一行包含用户和NULL的时间,另一行包含NULL的用户和一个时间的值。

I should note that you can define the loglist so ttime is defaulted to the current timestamp on the insert. 我应该注意,您可以定义loglist因此ttime默认为插入时的当前时间戳。 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 . 将始终设置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: 你应该alter loglist和修改ttimedefault的值CURRENT_TIMESTAMP ,然后您可以简化insert这样的命令:

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. 这应该是正常现象,因为您的loglist列表表可能应该loglist具有插入时刻的时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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