如何连接三行结果,从一个连接到多个连接到多个列

sbtkgmzw  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(292)

我必须先得到一对多连接的三个结果。例如

JOIN `company`.`Reason`
  ON ((`company`.`Reason`.`quality_id` = `company`.`Quality`.`id`)))

质量与理性有一对多的关系。
我需要在列reason1中显示reasons的第一个结果,在reason2中显示第二个,在reason3中显示第三个。
目前,我仅以这种方式显示一行结果:

`company`.`Reason`.`status`                                                AS `Reason`

我不知道它是如何工作的,它是如何选择一行的,哪一行?
我怎样才能做同样的事情,但只有3行和不同的列名?
质量

ID | a  | b
1  | a1 | b1 
2  | a2 | b2

原因

ID | quality_id  | status
1  | quality_id_1 | status_1 
2  | quality_id_1 | status_2
2  | quality_id_2 | status_1
2  | quality_id_2 | status_3

所以如果我想得到id 1质量的原因,我会得到

REASON_1 | REASON_2 | REASON_3
status_1 | status_2 | null
wfsdck30

wfsdck301#

您需要在按id from quality分区的reason表中创建一个排序,然后将其透视到希望返回的from quality列上。在下面的代码中,为了避免对基表进行修改,我使用了变量和子查询。

CREATE TABLE Quality (
  QualityID INT AUTO_INCREMENT,
  Value VARCHAR(50),
  PRIMARY KEY(QualityID)
  );

 CREATE TABLE Reason (
  ReasonID INT AUTO_INCREMENT,
  QualityID INT,
  Status varchar(50),
  PRIMARY KEY(ReasonID)
  );

  INSERT INTO Quality (Value) VALUES ('A1'),('A2');

  INSERT INTO Reason (QualityID, Status) VALUES (1,'Test1'),(1,'Test2'),(2,'Test3'),(2,'Test4'),(2,'Test5');

  SET @RC = 0;
SET @QC = 0;

SELECT
Q.Value,
MAX(IF(R.OrderNo = 1, R.Status, NULL)) AS Status1,
MAX(IF(R.OrderNo = 2, R.Status, NULL)) AS Status2,
MAX(IF(R.OrderNo = 3, R.Status, NULL)) AS Status3
FROM Quality Q
INNER JOIN (SELECT
@RC:=CASE
    WHEN @QC = QualityID THEN @RC + 1
    ELSE 1
END AS OrderNo,
@QC:=QualityID as QualityID,
Status
FROM Reason R)R ON R.QualityID = Q.QualityID
GROUP BY Q.Value;

相关问题