mysql将不同的行作为一行不同的列

时间:2014-06-15 10:53:03

标签: mysql database

假设我有以下表格

Applications
- id
- studentid
- company_id
-status

Company
-company_id
-company_name

Student
-studentid
-studentname

现在让学生申请3家公司

所以我希望结果显示如下。结果只有一行。

Id | student name | company 1 | company 2 | company 3 

我可以知道如何制作如上所述。我设法使用join语句执行多行。但是如何做到我想要的那个。

1 个答案:

答案 0 :(得分:-1)

我希望,它有效,

  SELECT A.studentid, S.studentname,
        (  SELECT X1.company_id
             FROM (  SELECT @rownum := @rownum + 1 AS position, Q1.company_id
                       FROM Applications Q1 JOIN (SELECT @rownum := 0) R1
                      WHERE Q1.studentid = A.studentid
                      ORDER BY Q1.id) X1
            WHERE X1.position = 1) AS company_1,
        (  SELECT X2.company_id
             FROM (  SELECT @rownum := @rownum + 1 AS position, Q2.company_id
                       FROM Applications Q2 JOIN (SELECT @rownum := 0) R2
                      WHERE Q2.studentid = A.studentid
                      ORDER BY Q2.id) X2
            WHERE X2.position = 2) AS company_2,
        (  SELECT X3.company_id
             FROM (  SELECT @rownum := @rownum + 1 AS position, Q3.company_id
                       FROM Applications Q3 JOIN (SELECT @rownum := 0) R3
                      WHERE Q3.studentid = A.studentid
                      ORDER BY Q3.id) X3
            WHERE X3.position = 3) AS company_3
    FROM Applications AS A INNER JOIN Student S ON A.studentid = S.studentid
GROUP BY A.studentid, S.studentname
ORDER BY A.studentid, S.studentname

AhmetVehbiOlgaç


AhmetVehbiOlgaç