来自mysql数据库的多表SELECT(在单个字段中返回多个项)

时间:2011-05-13 05:07:58

标签: mysql sql database

我需要一些认真的帮助。这是事情...... 假设我有一个带有字段(userId,name)的'users'表。现在我需要从其他表中获取与此用户相关的多项信息。有些项目很相似,所以需要捆绑在一起。

现在我还有其他几个表:

CREATE TABLE app.phones (
`id` INT NOT NULL AUTO_INCREMENT ,
`userId` INT NOT NULL ,
`phone` VARCHAR( 16 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB;

CREATE TABLE app.emails (
`id` INT NOT NULL AUTO_INCREMENT ,
`userId` INT NOT NULL ,
`email` VARCHAR( 32 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB;

CREATE TABLE app.contact_methods (
`id` INT NOT NULL AUTO_INCREMENT ,
`userId` INT NOT NULL ,
`method` ENUM( 'phone', 'email' ) NOT NULL,
`methodId` INT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB;

CREATE TABLE app.groups (
`id` INT NOT NULL AUTO_INCREMENT ,
`groupName` VARCHAR( 16 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB;

CREATE TABLE app.users_groups (
`id` INT NOT NULL AUTO_INCREMENT ,
`userId` INT NOT NULL ,
`groupId` INT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB;

正如您可能猜到的,每个用户可以拥有多个电子邮件,电话并成为多个群组的一部分。如何使用上面的所有表格显示如下表格?

+---------+-------------+-------------------+--------------+
|name     |phones       |emails             |groups        |
+---------+-------------+-------------------+--------------+
|John Doe |123-555-0101,|johndoe@mail.com,  |group1,group2,|
|         |123-555-0909 |johndoe2@mail.com  |group3        |
+---------+-------------+---------+---------+--------------+

更新:电子邮件和电话不应立即从他们的表中获取。表contact_methods包含引用这些表的条目。

1 个答案:

答案 0 :(得分:2)

试试这个尺寸

SELECT u.name, ph.phone, em.email, gr.groupName 
FROM users AS u, phones AS ph, emails AS em, groups AS gr 
WHERE (u.id = ph.userId) 
    AND (u.id = em.userId) 
    AND (u.id = gr.userId) 
GROUP BY u.id

或者连接值以获得一行(感谢@ chris-morgan):

SELECT u.name, 
    GROUP_CONCAT(ph.phone SEPARATOR ','), 
    GROUP_CONCAT(em.email SEPARATOR ','), 
    GROUP_CONCAT(gr.groupName SEPARATOR ',') 
FROM users AS u, phones AS ph, emails AS em, groups AS gr 
WHERE (u.id = ph.userId) 
    AND (u.id = em.userId) 
    AND (u.id = gr.userId) 
GROUP BY u.id