SQL - 仅选择不同的一列

时间:2015-10-13 13:13:49

标签: mysql sql

如何从几列中进行选择,但只选择其中一列的DISTINCT结果?这就是我现在所拥有的:

SELECT DISTINCT(ur.user_by), urs.username
    FROM 
          ( SELECT *
            FROM users 
            LIMIT 10
         ) AS ur
      LEFT JOIN 
          people AS urs 
        ON 
          ur.user_by = urs.username 

    LIMIT 10

虽然DISTINCT(user_by)不起作用。

3 个答案:

答案 0 :(得分:2)

带有GROUP BY urs.username

MAX(urs.username)会为您提供用户名的不同值:

SELECT ur.user_by, MAX(urs.username) AS username
FROM 
      ( SELECT *
        FROM users 
        LIMIT 10
     ) AS ur
  LEFT JOIN 
      people AS urs 
    ON 
      ur.user_by = urs.username 
 GROUP BY  ur.user_by
 LIMIT 10;

为了获得不同的值,您必须使用带有聚合函数的GROUP BY来为每个组仅选择一行。在您的情况下,MAX将使用username查找,并且只为每组user_by选择一个值。

<强>更新

要从users表中仅选择10个唯一身份用户,请在子查询本身内使用DISTINCT user_by LIMIT 10,如下所示:

SELECT ur.user_by, MAX(urs.username) AS username
FROM 
(
        SELECT DISTINCT user_by
        FROM users 
        LIMIT 10
 ) AS ur
  LEFT JOIN 
      people AS urs 
    ON 
      ur.user_by = urs.username 
 GROUP BY  ur.user_by
 LIMIT 10;

答案 1 :(得分:0)

尝试使用GROUP BY

SELECT ur.expire, ur.user_by, urs.username
    FROM 
          ( SELECT *
            FROM users 
            LIMIT 10
         ) AS ur
      LEFT JOIN 
          people AS urs 
        ON 
          ur.user_by = urs.username 
    GROUP BY ur.user_by, urs.username,ur.expire
    LIMIT 10

答案 2 :(得分:-1)

我相信DISTINCT(列)需要在您的选择列表中排在第一位吗?