我必须获得一对多连接的前三个结果。 例如
JOIN `company`.`Reason`
ON ((`company`.`Reason`.`quality_id` = `company`.`Quality`.`id`)))
质量与理性有一对多的关系。
我需要在REASON_1列中显示Reason的第一个结果,在REASON_2中显示第二个结果,在REASON_3中显示第三个结果。
此刻,我仅以这种方式显示一行结果:
`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
答案 0 :(得分:2)
您需要在原因表中创建一个排序,该表由按质量划分的id划分,然后在希望返回的按质量划分的列上进行排序。在下面的代码中,我使用了变量和子查询来完成此操作,以避免不得不对基表进行修改。
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;