简体   繁体   English

MySQL如何将一行内容复制到同一张表的多行

[英]How to copy the content of a row to multiple rows on the same table in MySQL

I want to copy a value of a row based on ID and then paste it to other column base on their IDs.我想根据 ID 复制一行的值,然后根据其 ID 将其粘贴到其他列。

For example, I want to update blocks with ID of 1, 2 to the value of blocks with the ID of 4. So basically I want to copy the content of ID 4 (or any other ID) and paste it to blocks with ID of 1,2 (or any other IDs) .例如,我想将 ID 为 1、2 的块更新为 ID 为 4 的块的值。所以基本上我想复制 ID 4(或任何其他 ID)的内容并将其粘贴到 ID 为1,2(或任何其他 ID)。

For example, I have a table called market and I want to copy the columns fruits and ripeness with ID of 4 to the same table and column with the ID of 1 and 2.例如,我有一个名为market的表,我想将 ID 为 4 的水果和成熟度列复制到 ID 为 1 和 2 的同一个表和列中。

ID | fruits | ripeness|
----------------------
1  | tomato | very    |
2  | apple  | little  |
3  | orange | very    |
4  | kiwi   | ripe    |

To:到:

ID | fruits | ripeness|
----------------------
1  | kiwi   | ripe    |
2  | kiwi   | ripe    |
3  | orange | very    |
4  | kiwi   | ripe    |

A table can join with itself with two different aliases一个表可以使用两个不同的别名与自身连接

UPDATE market f
CROSS JOIN market t
SET t.fruits = f.fruits, t.ripeness = f.ripeness
WHERE f.ID = 4
AND t.ID IN ( 1, 2 )

f for rows with ID 4, and t for rows with ID 1, 2. f表示 ID 为 4 的行, t表示 ID 为 1、2 的行。

It is said bad habit , that old-style comma-separated list of tables style was replaced with the proper ANSI JOIN syntax in the ANSI-92 SQL Standard (almost 30 years ago) and its use is discouraged. 据说坏习惯是,旧式的逗号分隔的表样式列表在 ANSI-92 SQL 标准(大约 30 年前)中被正确的 ANSI JOIN 语法所取代,并且不鼓励使用它。 If you really want to combine each row from both views, use the proper CROSS JOIN!如果您真的想合并来自两个视图的每一行,请使用正确的 CROSS JOIN! you just simply do it as per the following.您只需按照以下操作即可。

declare v_fruits varchar(50)
declare v_ripness varchar(50)

 -- SQLINES LICENSE FOR EVALUATION USE ONLY
 select fruits, ripness into v_fruits, v_ripness from market
 where Id=4

update market set fruits=v_fruits,ripness=v_ripness
where Id in (1,2)

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

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