如何避免LEFT JOIN查询中的重复记录?

时间:2014-06-18 17:43:34

标签: mysql sql database join

我有以下表格:

CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(40) NOT NULL,
  PRIMARY KEY (id)
  );
id | name    
---|-------------
 1 | John
 2 | Franck
 3 | Peter
...
CREATE TABLE emails (
  iduser INT NOT NULL,
  email VARCHAR(40) NOT NULL,
  PRIMARY KEY (iduser, email),
  );
ALTER TABLE emails 
ADD FOREIGN KEY (iduser)
REFERENCES users (id) ON DELETE CASCADE;
iduser | email
-------|---------------
     1 | john@hotmail.com
     1 | john@other.com
     2 | franck@gmail.com
...

我需要获得以下结果:

id | Name   | Email
---|--------|----
 2 | Franck | franck@gmail.com (just one of the two)
 1 | John   | john@hotmail.com
 3 | Peter  |

使用

SELECT users.id, users.name, emails.email
  FROM users LEFT JOIN emails ON emails.iduser = users.id
  ORDER BY users.name

返回两个John行,但我只需要其中一行(并且我还需要没有匹配电子邮件的行)。如何使用单个查询完成?

3 个答案:

答案 0 :(得分:1)

假设您不关心返回哪个电子邮件。

SELECT users.id, users.name, max(emails.email)
FROM users 
 LEFT JOIN emails ON emails.iduser = users.id
GROUP by user.id, users.name
ORDER BY users.name

答案 1 :(得分:1)

SELECT users.id, users.name, MAX(emails.email) AS Email
  FROM users 
  LEFT JOIN emails ON emails.iduser = users.id
GROUP BY users.id
ORDER BY users.name

答案 2 :(得分:0)

添加DISTINCT以返回唯一行和emails.email IS NULL

SELECT DISTINCT users.id, users.name, emails.email
FROM users LEFT JOIN emails ON emails.iduser = users.id
WHERE emails.email IS NULL
ORDER BY users.name