如何使用MySQL平展左连接的结果?

时间:2013-08-13 06:40:32

标签: mysql select join subquery left-join

我正在尝试创建一个查询,其中我加入USER表和ADDRESS_BOOK表,其中1个用户可能有多个地址(即结算,发货)。每个地址都是ADDRESS_BOOK表中的自己的条目。

ADDRESS_BOOK表中的每个条目都有一个USER_ID值,对应USER表中的一个条目。

我想得到以下结果:

____________________________
USER ID | BILLING | SHIPPING

现在我每USER_ID收到两个结果,一个用于SHIPPING地址,另一个用于BILLING地址。我需要在每个USER_ID获得一个结果,其中SHIPPINGBILLING信息(两个查询结果)被展平。

2 个答案:

答案 0 :(得分:4)

使用GROUP BY按用户ID对行进行分组,然后使用GROUP_CONCAT将所有条目作为单行进行分组。使用以下示例(我使用fullname而不是用户ID只是为了让它更容易看到):

CREATE TABLE user (
       user_id INT AUTO_INCREMENT PRIMARY KEY,
       fullname VARCHAR(32)
);

CREATE TABLE billing (
       user_id INT,
       billing VARCHAR(128)
);

CREATE TABLE shipping (
       user_id INT,
       shipping VARCHAR(128)
);

INSERT INTO user(fullname) VALUES ('Susan');
SET @last_id = LAST_INSERT_ID();
INSERT INTO billing VALUES
       (@last_id, 'Box 123');
INSERT INTO shipping VALUES
       (@last_id, '123 Oak Street'),
       (@last_id, '234 Pine Street');
INSERT INTO user(fullname) VALUES ('Mike');
SET @last_id = LAST_INSERT_ID();
INSERT INTO billing VALUES
       (@last_id, 'Box 12'),
       (@last_id, 'Deep Mine 3');
INSERT INTO shipping VALUES
       (@last_id, '4711 Iron Road');

此选择语句

SELECT fullname
     , group_concat(shipping)
     , group_concat(billing)
  FROM user JOIN billing USING (user_id)
            JOIN shipping USING (user_id)
GROUP BY fullname;

会给出这个结果:

+----------+--------------------------------+--------------------+
| fullname | Shipping                       | Billing            |
+----------+--------------------------------+--------------------+
| Mike     | 4711 Iron Road,4711 Iron Road  | Box 12,Deep Mine 3 |
| Susan    | 234 Pine Street,123 Oak Street | Box 123,Box 123    |
+----------+--------------------------------+--------------------+
2 rows in set (0.00 sec)

答案 1 :(得分:3)

这可能会有所帮助:

SELECT U.USER_ID,  
(SELECT ADDRESS FROM ADDRESS_BOOK WHERE USER_ID = U.USER_ID AND ADDRESS_TYPE = 'BILLING') AS BILLING,  
(SELECT ADDRESS FROM ADDRESS_BOOK WHERE USER_ID = U.USER_ID AND ADDRESS_TYPE = 'SHIPPING') AS SHIPPING 
FROM USER U;