当与另一个表

时间:2017-09-25 12:23:51

标签: mysql select distinct

这是查询:

SELECT a.id, a.userName,if(o.userId=1,'C',if(i.userId=1,'I','N')) AS relation 
       FROM tbl_users AS a 
       LEFT JOIN tbl_contacts AS o ON a.id = o.contactId 
       LEFT JOIN tbl_invites AS i ON a.id = i.invitedId 
  ORDER BY relation

返回输出如下:

+----+--------------+-------------+
| ID | USERNAME     | RELATION    | 
+----+--------------+-------------+
|  1 |          ray |           C | 
+----+--------------+-------------+
|  2 |         john |           I | 
+----+--------------+-------------+
|  1 |         ray  |           N | 
+----+--------------+-------------+

我需要通过检查id是否可能重复来从select查询中删除第三行。优先顺序如下:

C - >我 - > N.所以既然已经有了一张带有C的“光线”,我再也不想用I或N了。

我尝试添加distinct(a.id)但它不起作用。我该怎么做呢?

  
    

为什么DISTINCT不适用于此?

  

2 个答案:

答案 0 :(得分:1)

根据您提供的规格,您所要做的就是按ID和用户名分组,然后选择您可以找到的最低关系值(自C < I < N起)

SELECT a.id, a.userName, MIN(if(o.userId=1,'C',if(i.userId=1,'I','N'))) AS relation 
    FROM tbl_users AS a 
    LEFT JOIN tbl_contacts AS o ON a.id = o.contactId 
    LEFT JOIN tbl_invites AS i ON a.id = i.invitedId 
GROUP BY a.id, a.username

答案 1 :(得分:1)

如您在此manual page中所见,有多种方法可以获得分组最大/最小值。

最适合你的是第一个,如果行的顺序不能按字母顺序定义

在这种情况下,如果所需的顺序是z-a-m(参见Rams&#39;评论),则需要FIELD()函数。

所以你的答案是

SELECT 
a.id, 
a.userName,
if(o.userId=1,'C',if(i.userId=1,'I','N')) AS relation 
FROM tbl_users a
LEFT JOIN tbl_contacts AS o ON a.id = o.contactId 
LEFT JOIN tbl_invites AS i ON a.id = i.invitedId 
WHERE 
if(o.userId=1,'C',if(i.userId=1,'I','N')) = (
    SELECT 
    if(o.userId=1,'C',if(i.userId=1,'I','N')) AS relation 
    FROM tbl_users aa
    LEFT JOIN tbl_contacts AS o ON aa.id = o.contactId 
    LEFT JOIN tbl_invites AS i ON aa.id = i.invitedId 
    WHERE aa.id = a.id AND aa.userName = a.userName
    ORDER BY FIELD(relation, 'N', 'I', 'C') DESC 
    LIMIT 1
)

注意,您也可以像ORDER BY FIELD(relation, 'C', 'I', 'N')那样使其更具可读性/直观性。我反过来说,因为如果你有可能有一个&#39; X&#39;在关系中,FIELD()函数将返回0,因为X未指定为参数。因此,它将在C&#39;之前进行排序。通过排序降序和转动参数的顺序,这不可能发生。