在sql查询中在单行中显示多行

时间:2016-07-26 07:07:33

标签: sql sql-server

以下是我的表,请您参考 我正在使用SQL

员工表

emp_id(primary key)  -   emp_name            -  emp_mobile
1                         raju                  123456899
2                         hari                  454654562
3                         aravindth             545485454
4                         siva                  549855291

employeeTechnology 表:

emptech_id(primary key)  -  emp_id(foreign key)    -  technology_id(foreign key)
1                            1                               1
2                            1                               2
2                            1                               5
3                            2                               1
4                            2                               3
5                            3                               4
6                            3                               5
7                            4                               3
8                            4                               4

技术表:

technology_id(primary key)  -   tech_name
1                                 java-j2ee
2                                 Dot.net
3                                 DBA-SQL
4                                 big-data
5                                 SAP

我想这样输出:

emp_id             -    tech_name
1                        java-j2ee/Dot.net/SAP
2                        java-j2ee/DBA-SQL
3                        big-data/SAP
4                        DBA-SQL/big-data

我已经尝试过以下方法: select e.emp_id,t.technology_id from employee e,employeeTechnology et,technology t where e.emp_id =et.emp_id and et.technology_id = t.technology_id

2 个答案:

答案 0 :(得分:1)

您应该使用STUFF功能

SELECT
    e.emp_id, STUFF((SELECT '/' + t.tech_name 
     FROM
        dbo.employeeTechnology et 
     INNER JOIN
        dbo.technology t
     ON et.technology_id = t.technology_id
     WHERE
        et.emp_id = e.emp_id
     FOR XML PATH('')), 1, 1, '')
FROM
    employee e

答案 1 :(得分:0)

我尝试了上面的代码,但它在MySQL中不起作用。

    SELECT  e.emp_id, GROUP_CONCAT( DISTINCT t.`tech_name` ORDER BY `et`.`technology_id` ASC SEPARATOR '/' )  employee_name FROM employee e, employeeTechnology et, technology t  WHERE e.emp_id = et.emp_id AND et.technology_id = t.technology_id  GROUP BY `e`.`emp_id` 

现在我尝试了它的工作正常。我有一个问题,MySQL不支持STUFF功能吗?