MySQL - 使用相同的密钥更新兄弟姐妹

发布于 2024-12-09 06:26:26 字数 338 浏览 5 评论 0原文

尚未找到解决方案...虽然这可能是一个新手问题,但我无法克服...希望有人可以伸出援手。

我有一个 MySQL 表,其中包含:

块引用

     Col1  Col2
Row1 A     null
Row2 A     A1
Row3 A     null
Row4 B     null
Row5 B     B1
etc

> Blockquote

如何构建 SQL 更新来更新 Col2,以便 Col2 上的值替换 null,即 C2R1 和 C2R3 获取 A1,C2R4 获取 B1 ?

Couldn't find a solution yet... although it is probably a newbie question, I haven't been able to overcome... hope someone can give a hand.

I have a MySQL table that has:

Blockquote

     Col1  Col2
Row1 A     null
Row2 A     A1
Row3 A     null
Row4 B     null
Row5 B     B1
etc

> Blockquote

How do I construct an SQL update to update Col2, so that the values on Col2 replace the null, ie, C2R1 and C2R3 gets A1, and C2R4 gets B1 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你爱我像她 2024-12-16 06:26:26

您可以按如下方式计算所需的值:

CREATE TEMPORARY TABLE yourtemptable AS
SELECT yourtable.col1, T1.col2
FROM yourtable
JOIN
(
    SELECT col1, MAX(col2) AS col2
    FROM yourtable
    GROUP BY col1
) T1
ON yourtable.col1 = T1.col1

然后您可以删除/截断原始表并使用这些值重新创建它,或者如果您无法删除该表,则可以执行多表 更新

You can calculate the required values as follows:

CREATE TEMPORARY TABLE yourtemptable AS
SELECT yourtable.col1, T1.col2
FROM yourtable
JOIN
(
    SELECT col1, MAX(col2) AS col2
    FROM yourtable
    GROUP BY col1
) T1
ON yourtable.col1 = T1.col1

You can then either drop/truncate the original table and recreate it using these values, or if you can't drop the table you can instead perform a multi-table update.

凉世弥音 2024-12-16 06:26:26

尽管它可能不起作用(因为 MySQL 文档指出当前,您无法更新表并在子查询中从同一个表中进行选择。),但您应该尝试使用以下方法:

UPDATE table1 SET col2 = (SELECT t2.col1 FROM table1 t2 WHERE t2.col1 = table1.col1 AND NOT t2.col2 IS NULL LIMIT 1) WHERE table1.col2 IS NULL

Although it might not work (because the MySQL documentation states that Currently, you cannot update a table and select from the same table in a subquery.), you should try with something like:

UPDATE table1 SET col2 = (SELECT t2.col1 FROM table1 t2 WHERE t2.col1 = table1.col1 AND NOT t2.col2 IS NULL LIMIT 1) WHERE table1.col2 IS NULL
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文