如何在一行中列出多个结果?

时间:2015-09-23 19:10:13

标签: mysql

我想查询我的表以产生此输出。

enter image description here

以下是初始数据:

CREATE TABLE Order_Tester (
    OrderID int(11) NOT NULL default '0',
    TesterID int(11) NOT NULL default '0',
    PRIMARY KEY (OrderID,TesterID),
    KEY OrderID (OrderID),
    KEY TesterID (TesterID)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
INSERT INTO Order_Tester VALUES (1, 1);
INSERT INTO Order_Tester VALUES (1, 2);
INSERT INTO Order_Tester VALUES (1, 3);
INSERT INTO Order_Tester VALUES (1, 4);
INSERT INTO Order_Tester VALUES (2, 2);
INSERT INTO Order_Tester VALUES (2, 3);
INSERT INTO Order_Tester VALUES (3, 1);
INSERT INTO Order_Tester VALUES (3, 2);
INSERT INTO Order_Tester VALUES (4, 4);
CREATE TABLE Orders (
    ID int(11) NOT NULL auto_increment,
    Name varchar(50) default NULL,
    PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
INSERT INTO Orders VALUES (1, 'Order 1');
INSERT INTO Orders VALUES (2, 'Order 2');
INSERT INTO Orders VALUES (3, 'Order 3');
INSERT INTO Orders VALUES (4, 'Order 4');
CREATE TABLE Organizations (
    ID int(11) NOT NULL default '0',
    Name varchar(50) default NULL,
    PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
INSERT INTO Organizations VALUES (1, 'Auto-dealer.ru');
INSERT INTO Organizations VALUES (2, 'autoRATING.ru');
INSERT INTO Organizations VALUES (3, 'autoPotrebitel.ru');
CREATE TABLE Testers (
    ID int(11) NOT NULL auto_increment,
    FirstName varchar(50) default NULL,
    LastName varchar(50) default NULL,
    OrganizationID int(11) NOT NULL default '0',
    PRIMARY KEY (ID),
    KEY OrganizationID (OrganizationID)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;
INSERT INTO Testers VALUES (1, 'A', 'AA', 1);
INSERT INTO Testers VALUES (2, 'B', 'BB', 1);
INSERT INTO Testers VALUES (3, 'C', 'CC', 2);
INSERT INTO Testers VALUES (4, 'D', 'DD', 3);
ALTER TABLE `Order_Tester`
ADD CONSTRAINT order_tester_ibfk_2 FOREIGN KEY (TesterID) REFERENCES testers (ID),
ADD CONSTRAINT order_tester_ibfk_1 FOREIGN KEY (OrderID) REFERENCES orders (ID);

这是与测试人员相关的样本订单列表。此外,测试人员以逗号分隔,并在括号中列出他们所属的组织。如果列TestersName获得了属于同一组织的多个测试人员,则该名称不会重复,但最后只显示一次。

我试过......

SELECT CONCAT(orders.name) AS OrderName,
       CONCAT( FirstName ,'', LastName ) AS TesterName
FROM orders, testers,order_tester
WHERE orders.ID = OrderID
  AND testers.ID = TesterID

1 个答案:

答案 0 :(得分:0)

要将多个行组合在一起,请使用GROUP BY子句和GROUP_CONCAT来显示一个单元格中的所有分组行。

SELECT CONCAT(orders.name) AS OrderName ,
       GROUP_CONCAT(
         CONCAT( FirstName ,'', LastName, ' ', '(', Organizations.Name, ')' )
       ) AS TesterNames
FROM orders
JOIN order_tester  ON orders.ID = OrderID
JOIN testers       ON testers.ID = TesterID
JOIN organizations ON organizations.ID = OrganizationID
GROUP BY OrderName

Try it out yourself