0

所以我有一个可以在很多公司工作的员工,所以我有一个n to n关系,我怎样才能获得一个员工工作的公司,只用 sql 一行?

example
table - employee
Employeeid  employeename
1             mike

table company
companyId  CompanyName
1           cocacola
2             nokia
3              intel

table employeeCompany
id   employeeid  companyid
1       1            1
2       1            2
3       1            3

我想这个但不能

select Employeeid  , companyid 
from employeeCompany 
where employeeid  = 1 
group by Employeeid  , companyid
4

2 回答 2

2

在 Sql Server 中执行此操作的最简单方法是使用FOR XML PATH。神秘的部分.value('text()[1]','nvarchar(max)')处理特殊的 xml 字符。

select employee.*, companies.*
from Employee
OUTER APPLY
(
    select stuff ((SELECT ', ' + Company.CompanyName
      FROM EmployeeCompany
        INNER JOIN Company
           ON EmployeeCompany.CompanyId = Company.CompanyID
      WHERE EmployeeCompany.employeeid = Employee.EmployeeID
      ORDER BY Company.CompanyName
      FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)')
    , 1, 2, '') Companies
) companies

请参阅Sql Fiddle的演示。

于 2012-04-24T18:55:05.257 回答
0

听起来您想要类似于Group_ConcatSQL Server中的 mySQL 的东西?

如果您正在寻找一种方法来执行此操作,以便每个 companyid 位于单独的列中,那么使用动态 SQL 可能会遇到一些困难。在什么时候将它返回给应用程序并让它在自己的逻辑中处理它需要的东西可能会更容易?

顺便说一句,动态 SQL 逻辑会像这样,以防您想知道...注意它有多讨厌...这就是为什么我建议反对它。

select @highestCount = max(count(*))
from employeeCompany
group by Employeeid

declare createtemptable varchar(max), @filltableselect varchar(max), @filltablejoin varchar(max)
declare @currentCount int
set @currentCount = 0
set @createtemptable = 'CREATE TABLE #Temp (EmployeeID INT'
set @filltableselect = 'INSERT INTO #Temp SELECT EmployeeCompany0.EmployeeID, EmployeeCompany0.CompanyID'
set @filltablejoin = 'FROM EmployeeCompany AS EmployeeCompany0'

while(@currentCount < @highestCount)
begin
    set @createtemptable = @createtemptable + ', CompanyID' 
        + CAST(@currentCount AS VARCHAR(2)) + ' INT'

    if(@currentCount > 0)
    begin
        set @filltableselect = @filltableselect + ', EmployeeCompany' 
            + CAST(@currentCount AS VARCHAR(2)) + '.CompanyId'

        set @filltablejoin = @filltablejoin 
            + 'LEFT JOIN EmployeeCompany AS EmployeeCompany' 
            + CAST(@currentCount AS VARCHAR(2)) 
            + ' ON EmployeeCompany0.EmployeeID = EmployeeCompany' 
            + CAST(@currentCount AS VARCHAR(2)) + '.EmployeeID'
    end

    set @currentCount = @currentCount + 1
end
set @createtemptable = @createtemptable + ')'
--This next line can be whatever you need it to be
set @filltablejoin = @filltablejoin + 'WHERE employeeCompany0.EmployeeID = 1'

exec @createtemptable 
exec @filltableselect + @filltablejoin
于 2012-04-24T17:15:55.040 回答