[英]Combine Update and Select Query
I got two MySQL working fine and i'm trying to find a way to combine them into one single query. 我有两个MySQL正常工作,我试图找到一种将它们组合成一个查询的方法。
First, it selects ID of an employee. 首先,它选择员工的ID。
SELECT 'ID' FROM `employee` ORDER BY ID DESC LIMIT 1;
Let's say it returns ID 100; 假设它返回ID 100;
Then update data of employees whose ID is 100 然后更新ID为100的员工数据
UPDATE 'LOG' SET `TIME_EXIT`='2013/02/22' WHERE `ID`='100';
Can i do it all in a single query? 我可以在一个查询中完成所有操作吗?
Just add them together: 只需将它们添加在一起:
UPDATE LOG SET TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM employee
ORDER BY ID DESC
LIMIT
);
But based on that code currently it'll only ever update the last employee
, you will need to select the correct employee
by using some other identifier to ensure you have the correct one. 但是根据当前的代码,它只会更新最后一位
employee
,您将需要使用其他一些标识符来选择正确的employee
,以确保您拥有正确的employee
。
UPDATE LOG SET TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM employee
WHERE NAME = 'JOHN SMITH'
ORDER BY ID DESC
LIMIT 1
);
It's now a few months old, but maybe helps you or others finding this via google… 现在已经几个月了,但是也许可以帮助您或其他人通过google找到这个…
If you want to UPDATE a field in the same selected table use this: 如果要更新同一选定表中的字段,请使用以下命令:
UPDATE LOG SET
TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM (
SELECT ID
FROM LOG
WHERE whatEverYouWantToCheck = whateverYouNeed
) AS innerResult
)
So, you SELECT id from a subselect. 因此,您可以从子选择中选择ID。 If you try to subselect it directly, mySQL quites with your error message
You can't specify target table 'log' for update in FROM clause
, but this way you hide your subsubquery in a subquery and that seems to be fine. 如果尝试直接对其进行子选择,则mySQL会显示错误消息,
You can't specify target table 'log' for update in FROM clause
,但是这样可以将子子查询隐藏在子查询中,这似乎很好。 Don't forget the AS innerResult
to avoid getting the error message #1248 - Every derived table must have its own alias
. 不要忘记
AS innerResult
以避免收到错误消息#1248 - Every derived table must have its own alias
AS innerResult
#1248 - Every derived table must have its own alias
。 Also match the subsubquery field name to the subquery field name in case you do something like SELECT COUNT(*)
or SELECT CONCAT('#', ID)
如果您执行
SELECT COUNT(*)
或SELECT CONCAT('#', ID)
还应将子查询字段名称与子查询字段名称匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.