用逗号分割字符串

时间:2019-12-03 14:42:12

标签: mysql

Am使用msql单独编写了一个字符串,它非常适合三个字符串,例如“ eat,go,take” 但是当我只使用两个字符串时,它将在第三个字符串上重复第二个字符串。

如果少于三个字符串,我如何将其设置为仅显示一个空字符串

SELECT
    SUBSTRING_INDEX(string, ',', 1) AS pri,
    SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 2), ',', -1) AS sec,
    SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 3), ',', -1) AS ter
FROM team WHERE playerId= 98538;

因此,如果第三个字符串为空,则在第三个结果上重复第二个字符串 我如何设置它,如果最后一个字符串为空,则仅显示一个空字符串。

这是如果我只有两个分开的字符串显示的剪裁信息

enter image description here

1 个答案:

答案 0 :(得分:0)

假设string列中的电子邮件格式如下:

threeEmails1@gmail.com,threeEmails2@gmail.com,threeEmails3@gmail.com

我倾向于为此使用子查询,然后在输出结果时检查列是否与先前的结果匹配:

SELECT  pri,
        CASE
          WHEN sec = pri THEN NULL
          ELSE sec
        END AS sec,
        CASE
          WHEN ter = pri THEN NULL
          WHEN ter = sec THEN NULL
          ELSE ter
        END AS ter
  FROM  (
        SELECT  SUBSTRING_INDEX(string, ',', 1) AS pri,
                SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 2), ',', -1) AS sec,
                SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 3), ',', -1) AS ter
          FROM  team 
          WHERE playerId = 98538
        ) a

这是一个可行的示例,其中三行分别包含3、2和1个电子邮件地址,以显示不同的结果:

CREATE TABLE team (playerID INT, string VARCHAR(100));
INSERT INTO team VALUES (98538, 'threeEmails1@gmail.com,threeEmails2@gmail.com,threeEmails3@gmail.com'),
                        (98538, 'twoEmails1@gmail.com,twoEmails2@gmail.com'),
                        (98538, 'oneEmail1@gmail.com');

SELECT  pri,
        CASE
          WHEN sec = pri THEN NULL
          ELSE sec
        END AS sec,
        CASE
          WHEN ter = pri THEN NULL
          WHEN ter = sec THEN NULL
          ELSE ter
        END AS ter
  FROM  (
        SELECT  SUBSTRING_INDEX(string, ',', 1) AS pri,
                SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 2), ',', -1) AS sec,
                SUBSTRING_INDEX(SUBSTRING_INDEX(string, ',', 3), ',', -1) AS ter
          FROM  team 
          WHERE playerId = 98538
        ) a

输出:

pri                     sec                     ter
threeEmails1@gmail.com  threeEmails2@gmail.com  threeEmails3@gmail.com
twoEmails1@gmail.com    twoEmails2@gmail.com    (null)
oneEmail1@gmail.com     (null)                  (null)

要查看其实际效果,请查看此fiddle

注意:该选项适用于最多三个电子邮件地址。在您的示例中,您似乎表明它足以解决您的问题,但是如果您在单个字符串中包含三个以上的电子邮件,则需要调整解决方案。如果您有 n 个电子邮件(未定义数量),则此解决方案可能不合适。