sql循环连接?

aurhwmvo  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(263)

如何连接sql列值并用逗号(',')分隔。
注意它也应该在null处终止。
考虑一个表模式(假设所有数据类型都是varchar(100))

c1s | c2s | c3s | c4s |  c5s  | c6s | c7s
a   | b   | c   | d   | null  | f   | g

所需输出应为:

a, b, c, d

使用mysql xampp

bvuwiixz

bvuwiixz1#

假设您有一个while循环,并且希望使用该循环创建sql或字符串。
下面的代码片段将帮助您。这只是一个sudo代码,您需要根据您的需求进行构建:

cnt = 1;
noOfPartitions = 20;
SET @innerQuery = '';
SET @alterQuery = CONCAT('select query ..........( ') ;
WHILE cnt <= noOfPartitions DO
    SET @innerQuery = CONCAT('criteria .....');
    SET cnt = cnt + 1;
    IF cnt <= noOfPartitions THEN
        SET @innerQuery = CONCAT(@innerQuery, ', ');
    ELSE
        SET @innerQuery = CONCAT(@innerQuery, ');');
    END IF;
END WHILE;
SET @alterQuery = CONCAT(@alterQuery, @innerQuery);
SELECT @alterQuery;

这样您就可以创建动态sql或创建字符串。

o4tp2gmn

o4tp2gmn2#

如果你真的需要这个,你可以用concat\ws。

SELECT CONCAT_WS(",", t.foo, t.foo1, t.foo2) AS myfield FROM mytable t

相关问题