从同一列中选择多行 - 加入

时间:2016-02-10 04:38:49

标签: mysql sql-server database join

我有三个表:Ses userSes MovesMoves

  • Ses user包含iduserses-id列。
  • Ses Moves包含ses-idmove-id列。
  • Moves包含idname列。

我通过Ses userSes Movesid加入ses-id。我还通过Ses MovesMovesmove-id加入了id

唯一的问题是Moves表中有多个具有相同ID的行,所以它看起来像这样:

+------+-=---+
|Ses ID| Name|
+------+-----+
|  10  | Bite|
+------+-----+
|  10  | Eat |
+------+-----+
|  10  |Crush|
+------+-----+
|  10  |Punch|
+------+-----+
|  10  |Stare|
+------+-----+
|  10  | Rest|
+------+-----+

我希望SQL语句返回如下内容:

+------+-----------+-----------+-----------+-----------+-----------+-----------+
|Ses ID|Name Move 1|Name Move 2|Name Move 3|Name Move 4|Name Move 5|Name Move 6|
+------+-----------+-----------+-----------+-----------+-----------+-----------+
|  10  |   Bite    |   Eat     |   Crush   |   Punch   |  Stare    |   Rest    |
+------+-----------+-----------+-----------+-----------+-----------+-----------+

如何让它归还?

如果知道有用,我使用PHP来运行查询。

1 个答案:

答案 0 :(得分:0)

使用动态SQL这不是一件难事(假设您不知道给定Ses ID可能具有的最大名称数。这是一个示例:

SET NOCOUNT ON;

-- CREATE TABLE #table ([Ses ID] INT, Name NVARCHAR(255));
-- INSERT #table VALUES (10, 'Bite'),(10,'Eat'),(10,'Crush'),(10,'Punch'),(9,'Hugs'),(9,'Kisses');

DECLARE @SQL NVARCHAR(4000) = '
WITH CTE AS (
    SELECT [Ses ID], Name, ROW_NUMBER() OVER (PARTITION BY [Ses ID] ORDER BY Name) RN
    FROM #table)
SELECT [Ses ID]'
, @MaxRN INT = (SELECT MAX(RN)
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY [Ses ID] ORDER BY Name) RN
    FROM #table) T)
, @i INT = 1;

WHILE @i <= @MaxRN BEGIN
    SET @SQL += ', (SELECT Name FROM CTE WHERE RN = ' + CAST(@i AS NVARCHAR(255)) + ' AND [Ses ID] = C.[Ses ID]) [Name Move ' + CAST(@i AS NVARCHAR(255)) + ']';
    SET @i += 1;
END

SET @SQL += '
FROM CTE C
GROUP BY [Ses ID]
ORDER BY [Ses ID]';

EXEC(@SQL);

-- DROP TABLE #table;