4

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

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

我想得到以下结果:

____________________________
USER ID | BILLING | SHIPPING

现在我得到两个结果USER_ID,一个是SHIPPING地址,一个是BILLING地址。我需要在每个信息(两个查询结果)被展平的地方USER_ID得到一个结果。SHIPPINGBILLING

4

2 回答 2

6

用于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)
于 2013-08-13T07:41:30.933 回答
4

这可能会有所帮助:

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;
于 2013-08-13T06:53:12.550 回答