我试图获取数据库中所有用户的列表,但是当我运行以下查询时:
SELECT cu.user_name AS username, cu.display_name AS displayname,
cm.lower_parent_name AS group, cu.email_address AS email
FROM cwd_user AS cu
INNER JOIN cwd_membership AS cm
ON cu.directory_id = cm.directory_id
AND cu.lower_user_name = cm.lower_child_name
AND cm.membership_type = 'GROUP_USER'
WHERE cm.lower_parent_name LIKE 'zz%'
ORDER BY cu.user_name;
我得到重复的条目(确定,因为我有同一个用户的多个值),但我只对小写的一个感兴趣。
+------------------------------------------------------------------+
| username | displayname | group | email |
+------------------------------------------------------------------+
| firstname.lastname | Firstname Lastname | zz group | f.l@a.com |
| Firstname.Lastname | Firstname Lastname | zz group | F.L@a.com |
+------------------------------------------------------------------+
我只想要其中一个用户(最好是第一个用户),所以我尝试了以下SQL查询:
SELECT t.user_name, cu.display_name, cm.lower_parent_name,
cu.email_address
FROM (
SELECT cu.user_name
FROM cwd_user AS cu
INNER JOIN cwd_membership AS cm ON cu.directory_id=cm.directory_id
AND cu.lower_user_name=cm.lower_child_name
AND cm.membership_type='GROUP_USER'
WHERE cm.lower_parent_name LIKE 'zz%'
GROUP BY LOWER(cu.user_name) ) u JOIN cwd_user t ON t.user_name =
u.user_name ORDER BY t.user_name;
但没有运气。我的SQL并不好,所以我被困在这里。
有什么想法吗?
答案 0 :(得分:1)
您可以在子选择中选择适当的值并使用正确的别名引用,您应该使用distinct而不是group by
Person EffectiveDate
123 1/1/2016
123 2/1/2016
123 4/1/2016
123 5/1/2016
Expected result would be
123 3/1/2016
如果您只需要小写的user_name,则可以尝试二进制低级
SELECT distinct
t.user_name
, u.display_name
, u.lower_parent_name
, u.email_address
FROM (
SELECT
cu.user_name
, cu.display_name
, cm.lower_parent_name
, cu.email_address
FROM cwd_user AS cu
INNER JOIN cwd_membership AS cm ON cu.directory_id=cm.directory_id
AND cu.lower_user_name=cm.lower_child_name
AND cm.membership_type='GROUP_USER'
WHERE cm.lower_parent_name LIKE 'zz%'
) u
JOIN cwd_user t ON t.user_name = u.user_name
ORDER BY t.user_name;
答案 1 :(得分:0)
SELECT distinct (t.user_name), cu.display_name, cm.lower_parent_name,
cu.email_address
FROM (
SELECT cu.user_name
FROM cwd_user AS cu
INNER JOIN cwd_membership AS cm ON cu.directory_id=cm.directory_id
AND cu.lower_user_name=cm.lower_child_name
AND cm.membership_type='GROUP_USER'
WHERE cm.lower_parent_name LIKE 'zz%'
GROUP BY LOWER(cu.user_name) ) u JOIN cwd_user t ON t.user_name =
u.user_name ORDER BY t.user_name;
在SQL SERVER中,DISTINCT关键字只选择不同的数据。
答案 2 :(得分:0)
我最终在bash脚本中创建了两个单独的查询,这样就可以解决这个问题。