MySQL:当电子邮件有多个附件时,防止重复行

时间:2013-09-29 16:06:36

标签: mysql duplicates

这是我用于在一个文件夹中显示电子邮件的MySQL查询(当然是精简的)......

SELECT em.id
FROM email_messages AS em 
LEFT JOIN email_attachments AS ea on ea.id_email=em.id 
WHERE em.id='4'

问题是,如果电子邮件包含多个附件,则相同的电子邮件会出现两次,例如email_messageid 4。

如果不更改SQL表的结构,如何返回任何值(例如1)来表示电子邮件具有附件而不返回重复的行?

1 个答案:

答案 0 :(得分:1)

添加DISTINCT以仅获取唯一值

SELECT DISTINCT em.id
FROM   email_messages AS em 
       LEFT JOIN email_attachments AS ea 
          ON ea.id_email = em.id 
WHERE  em.id = '4'

GROUP BY条款

SELECT em.id
FROM   email_messages AS em 
       LEFT JOIN email_attachments AS ea 
          ON ea.id_email = em.id 
WHERE  em.id = '4'
GROUP  BY em.id