我在使用从另一个表转置的列更新表时遇到问题。我在这里调查并接近解决方案,但我仍然没有达到目的。
我有一个表tbl_g08t1
,其中包含以下列以及其他未包含的列(第1行:列名称):
shl62 carrno typ stat 50 71 72 73 74 75 76
747 35712528 0 6 29 (NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
747 35722615 0 6 29 (NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
747 35722625 0 6 29 (NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
747 35722664 0 6 29 (NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
821 35136730 0 8 (NULL)(NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
821 35722678 0 8 29 (NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
821 35833255 0 6 (NULL)(NULL) (NULL) (NULL) (NULL) (NULL) (NULL)
我有第二个表tbl_s80t1
,其中包含freetexts,它看起来像:
sysfromt sysshort freecode freetext
G08T1 35722652 98 101
G08T1 35722652 132 KCF9F27
G08T1 35722664 50 29
G08T1 35722664 71 20171004
G08T1 35722664 74 01Y
G08T1 35722664 75 3
G08T1 35722664 76 A17108176
G08T1 35722664 97 8397080
G08T1 35722664 98 101
G08T1 35722664 132 KCF9F13
G08T1 35722678 50 29
G08T1 35722678 71 20171005
G08T1 35722678 74 01Y
G08T1 35722678 75 3
G08T1 35722678 76 D1718496
G08T1 35722678 97 8395896
G08T1 35722678 98 101
G08T1 35722678 132 KCF9F27
G08T1 35722684 8 2017-10-05 09:53 C:3 Out:9 General fault!
G08T1 35722684 8 2017-10-05 09:54 C:3 Out:9 General fault!
G08T1 35722684 50 29
我正在尝试将这两个表与
合并`tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND `tbl_s80t1`.`sysfromt` = 'G08T1'
并根据freecode
转置第二行的某些行,最后我得到了以下代码:
USE general_db;
UPDATE tbl_g08t1
LEFT JOIN `tbl_s80t1` ON (`tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND
`tbl_s80t1`.`sysfromt` = 'G08T1')
SET
`50` = (SELECT MAX(`tbl_s80t1`.`freetext`) WHERE `tbl_s80t1`.`freecode` = 50),
`71` = (SELECT MAX(`tbl_s80t1`.`freetext`) WHERE `tbl_s80t1`.`freecode` = 72),
`72` = (SELECT MAX(`tbl_s80t1`.`freetext`) WHERE `tbl_s80t1`.`freecode` = 73),
`76` = (SELECT MAX(`tbl_s80t1`.`freetext`) WHERE `tbl_s80t1`.`freecode` = 76)
问题是只更新了一列50
,所有其他71...76
都具有所有(NULL)值。我希望那里有freetext
个值,当然freecode
值是相关的。
好吧,我不知道我是否已经清楚......或者更加困惑...... 谢谢你的提示。
绘
PS 在运行查询时,我收到消息
33278 row(s) affected, 64 warning(s): 1265 Data truncated for column '50' at row 1
答案 0 :(得分:0)
问题出在你的set子句中。使用MAX()和SELECT是一个子查询,并没有引用JOIN子句。他们独立于此。我认为这可能有用:
USE general_db;
UPDATE tbl_g08t1
SET
`50` = (SELECT MAX(`tbl_s80t1`.`freetext`) FROM tbl_s80t1 WHERE `tbl_s80t1`.`freecode` = 50 AND `tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND `tbl_s80t1`.`sysfromt` = 'G08T1')),
`71` = (SELECT MAX(`tbl_s80t1`.`freetext`) FROM tbl_s80t1 WHERE `tbl_s80t1`.`freecode` = 71 AND `tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND `tbl_s80t1`.`sysfromt` = 'G08T1')),
`72` = (SELECT MAX(`tbl_s80t1`.`freetext`) FROM tbl_s80t1 WHERE `tbl_s80t1`.`freecode` = 73 AND `tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND `tbl_s80t1`.`sysfromt` = 'G08T1')),
`76` = (SELECT MAX(`tbl_s80t1`.`freetext`) FROM tbl_s80t1 WHERE `tbl_s80t1`.`freecode` = 76 AND `tbl_g08t1`.`carrno` = `tbl_s80t1`.`sysshort` AND `tbl_s80t1`.`sysfromt` = 'G08T1'))
没有SQL小提琴,我无法测试它。
答案 1 :(得分:0)
谢谢!有用!我只需要将列50...76
的长度从VARCHAR 50更改为255.只有一个额外的")"在每个要删除的陈述结束时。
执行时间非常好:15秒更新> 3百万条记录。