表創建如何克服MySQL的子查詢返回多個1行「的錯誤,並選擇所有相關記錄
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, '[email protected]'), (1, '[email protected]'), (1, '[email protected]'),
(2, '[email protected]'), (2, '[email protected]'), (2, '[email protected]'),
(3, '[email protected]'), (3, '[email protected]'), (3, '[email protected]');
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錯誤'子查詢返回多於一行'併爲特定用戶選擇所有相關電子郵件地址,如下所示。謝謝。
+----------+-------------------------------------------------+
| name | email |
+----------+-------------------------------------------------+
| Mark | [email protected], [email protected], [email protected] |
| Tom | [email protected], [email protected], [email protected] |
| Robin | [email protected], [email protected], [email protected] |
+----------+----------+--------------------------------------+
GROUP_CONCAT是一個possibility-但我真的懷疑這是否是一種有用的方式來返回數據。 – Strawberry