Search code examples
mysqlsubquerymysql-error-1242

How to overcome MySQL 'Subquery returns more than 1 row' error and select all the relevant records


Table creation

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`)
);

Data insertion

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 query

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;    

With the use of above my MySQL query, how can I avoid the MySQL Error 'Subquery returns more than 1 row' and select the all the relevant email address for particular User as below. Thanks.

+----------+-------------------------------------------------+
|   name   |                     email                       |
+----------+-------------------------------------------------+
|   Mark   | [email protected], [email protected], [email protected]    |
|   Tom    | [email protected], [email protected], [email protected]       |
|   Robin  | [email protected], [email protected], [email protected] |                   
+----------+----------+--------------------------------------+

Solution

  • GROUP_CONCAT with SEPARATOR and simplify your query a bit:

    SELECT users.name AS name,
    (SELECT GROUP_CONCAT(email_address.email_address SEPARATOR ', ')
    FROM email_address
    WHERE email_address.user_id = users.id) AS email
    FROM users
    

    Reference: https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat