您可以这样存储您的数据,假设所有电子邮件都是唯一的(我在UNIQUE KEY
那里添加)
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE `emails` (
`email` varchar(50) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`email`),
KEY `user_id` (`user_id`)
) DEFAULT CHARSET=utf8;
您可以像这样检索特定电子邮件的数据:
SELECT users.*, emails.email
FROM users
JOIN emails ON users.id = emails.user_id
WHERE emails.email = 'some_mail@example.com'
您还可以选择用户拥有的所有电子邮件,如下所示:
SELECT users.*, GROUP_CONCAT(emails.email)
FROM users
LEFT JOIN emails ON users.id = emails.user_id
WHERE users.id = 1234
GROUP BY users.id