用于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)