代码之家  ›  专栏  ›  技术社区  ›  Iustin Beceneagă

如何将一个MySQL行显示为多行?

  •  0
  • Iustin Beceneagă  · 技术社区  · 7 年前

    我需要帮助。 我有一个简单的mysql查询:

    select '1,2,3,4,5,6' as Col1 from dual;
    

    表1:

    Col1
    1,2,3,4,5,6
    

    我还有另一张桌子2:

    service_id    service_name
    1             Service1
    2             Service2
    

    我尝试了下一个查询,但没有工作:

    select service_name from table2 where service_id in (select col1 from table1)
    

    任何帮助都将不胜感激!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Michał Turczyn    7 年前

    试试这个:

    create table `dual` (Col1 varchar(100));
    insert into `dual` values ('1,2,3,4,5,6');
    
    create table table2 (service_id int, service_name varchar(100));
    insert into table2 values
    (1, 'Service1'),
    (2, 'Service2');
    

    T-SQL:

    select service_name from table2 t2
    where exists(
        select 1 from `dual` d
        where locate(concat(',', t2.service_id, ','), concat(',', d.Col1, ',')) > 0
    );
    
        2
  •  0
  •   SeanW333    6 年前

    只有当服务ID为“1,2,3,4,5,6”时,“in”子句才有效。我可以看到您正在尝试做什么,但是数据库将col1的结果视为包含所有逗号的整个数字字符串,而不是单个数字本身。如果硬编码为“Where in(1,2,3,4,5,6)”,您将得到匹配项。您可以联接表并使用like,而不是使用“in”子句。

    SELECT 
        table2.service_name 
    FROM
        table2
    LEFT OUTER JOIN
        table1
        ON
        table1.col1 LIKE CONCAT('%', table2.service_id, '%')
    WHERE 
        table1.col1 IS NOT NULL
    

    我想这会满足你的要求。