如何从几列中进行选择,但只选择其中一列的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)
不起作用。
答案 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(列)需要在您的选择列表中排在第一位吗?