表创建
CREATE TABLE `users` (
`id` INT UNSIGNED NOT NULL,
`name` VARCHAR(100) NOT NULL,
PRIMARY KEY(`id`)
);
CREATE TABLE `email_address` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`email_address` VARCHAR(50) NOT NULL,
INDEX pn_user_index(`user_id`),
FOREIGN KEY (`user_id`) REFERENCES users(`id`) ON DELETE CASCADE,
PRIMARY KEY(`id`)
);
数据插入
INSERT INTO users (id, name) VALUES (1, 'Mark'), (2, 'Tom'), (3, 'Robin');
INSERT INTO email_address (user_id, email_address) VALUES
(1, 'mark@gmail.com'), (1, 'mark@yahoo.com'), (1, 'mark@msn.com'),
(2, 'tom@gmail.com'), (2, 'tom@yahoo.com'), (2, 'tom@msn.com'),
(3, 'robin@gmail.com'), (3, 'robin@yahoo.com'), (3, 'robin@msn.com');
SQL查询
SELECT usr.name AS name
, (SELECT email.email_address
FROM email_address AS email
WHERE email.user_id = usr.id) AS email
FROM users AS usr;
使用上面的 MySQL 查询,如何避免 MySQL 错误“子查询返回超过 1 行”并选择特定用户的所有相关电子邮件地址,如下所示。谢谢。
+----------+-------------------------------------------------+
| name | email |
+----------+-------------------------------------------------+
| Mark | mark@gmail.com, mark@yahoo.com, mark@msn.com |
| Tom | tom@gmail.com, tom@yahoo.com, tom@msn.com |
| Robin | robin@gmail.com, robin@yahoo.com, robin@msn.com |
+----------+----------+--------------------------------------+