I need some serious help. Here’s the thing…
Assume I have a ‘users’ table with fields(userId, name). Now I need to grab multiple items of info from other table relating to this user. Some of the items are similar so need to be bundled together.
Now I also have several other tables:
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;
As you might guess, each user can have multiple emails, phones and be part of multiple groups. How would I display a table like below using all the tables above?
+---------+-------------+-------------------+--------------+
|name |phones |emails |groups |
+---------+-------------+-------------------+--------------+
|John Doe |123-555-0101,|johndoe@mail.com, |group1,group2,|
| |123-555-0909 |johndoe2@mail.com |group3 |
+---------+-------------+---------+---------+--------------+
UPDATE: Emails and Phones should not be taken immediately from their tables. The table contact_methods contains entries which reference those tables.
Try this for size
Or to concatenate the values to get one row (thanks @chris-morgan):