在同一个表中联合两列并将结果保存到mysql中同一个表中的其他列中

时间:2017-11-21 16:45:46

标签: java mysql

我是初学者,所以我需要你的帮助来修复我上一个项目的程序。 我希望合并frequent1xfrequent2x两列,并将结果存储到列frequent2中。

我使用此查询..

Insert into tvfrequent (no, frequent1, frequent1x, frequent2x, frequent2, frequent3, frequent4, frequent5, support)
SELECT no,
SUBSTRING_INDEX( unixdatetime , ' ', 1 ) AS frequent1,                   
(SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' ', 2 ),' ',-1) AS frequent1x) union (SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 2 ),' -1 ',-1) AS frequent2x) As frequent2,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 3 ),' -1 ',-1) AS frequent3,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 4 ),' -1 ',-1) AS frequent4,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 5 ),' -1 ',-1) AS frequent5,
SUBSTRING_INDEX( unixdatetime , ' -1 ', -1 ) AS support
FROM tspade

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

Insert into tvfrequent (no, frequent1, frequent1x, frequent2x, frequent2, frequent3, frequent4, frequent5, support)
SELECT no,
SUBSTRING_INDEX( unixdatetime , ' ', 1 ) AS frequent1,                   
concat
      (
       SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' ', 2 ),' ',-1)
       ,
       " "
       ,
       SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 2 ),' -1 ',-1)      
      ) As frequent2,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 3 ),' -1 ',-1) AS frequent3,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 4 ),' -1 ',-1) AS frequent4,
SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 5 ),' -1 ',-1) AS frequent5,
SUBSTRING_INDEX( unixdatetime , ' -1 ', -1 ) AS support
FROM tspade;

替代方法:

Insert into tvfrequent (no, frequent1, frequent1x, frequent2x, frequent2, frequent3, frequent4, frequent5, support)
    SELECT no,
    SUBSTRING_INDEX( unixdatetime , ' ', 1 ) AS frequent1,                   
    (case
        when
           (SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' ', 2 ),' ',-1))
       =          
           (SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 2 ),' -1 ',-1))
        then
           (SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' ', 2 ),' ',-1))
        else
            (concat
                   (
                     SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' ', 2 ),' ',-1)
                       ,
                      " "
                       ,
                     SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 2 ),' -1 ',-1)      
                   )
           )           
    ) As frequent2,    
    SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 3 ),' -1 ',-1) AS frequent3,
    SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 4 ),' -1 ',-1) AS frequent4,
    SUBSTRING_INDEX(SUBSTRING_INDEX( unixdatetime , ' -1 ', 5 ),' -1 ',-1) AS frequent5,
    SUBSTRING_INDEX( unixdatetime , ' -1 ', -1 ) AS support
    FROM tspade;