编辑我拥有的SQL版本(mysql 5.7)不支持row_number()
...我可以使用哪种替代方法?
我研究发现,使用row_number()
可以在哪里应用查询...我要检查的列是user_id
racid
和ios
< / p>
SELECT
ur.user_id,
u.racid,
u.fname,
u.lname,
u.email,
u.last_login,
ur.role_id,
r.name AS role_name,
i.device_token AS ios,
dg.group_name,
dg.ad_group,
a.device_token AS android
FROM
users AS u
LEFT OUTER JOIN
user_roles AS ur ON u.id = ur.user_id
LEFT OUTER JOIN
roles AS r ON ur.role_id = r.id
LEFT OUTER JOIN
ios_tokens AS i ON u.racid = i.racf_id
LEFT OUTER JOIN
android_tokens AS a ON u.racid = a.racf_id
LEFT OUTER JOIN
dashboard_groups AS dg ON dg.role_id = r.id
加入后的当前表
user_id, racid, fname, lname, email, last_login, role_id, role_name, ios, group_name, ad_group, android
答案 0 :(得分:2)
您可以尝试在下面将其用于mysql 8 +
select * from
(SELECT
ur.user_id,
u.racid,
u.fname,
u.lname,
u.email,
u.last_login,
ur.role_id,
r.name AS role_name,
i.device_token AS ios,
dg.group_name,
dg.ad_group,
a.device_token AS android,row_number() over(partition by ur.user_id,u.racid,i.device_token order by ur.user_id,
u.racid,i.device_token) as rn
FROM
users AS u
LEFT OUTER JOIN
user_roles AS ur ON u.id = ur.user_id
LEFT OUTER JOIN
roles AS r ON ur.role_id = r.id
LEFT OUTER JOIN
ios_tokens AS i ON u.racid = i.racf_id
LEFT OUTER JOIN
android_tokens AS a ON u.racid = a.racf_id
LEFT OUTER JOIN
dashboard_groups AS dg ON dg.role_id = r.id
)X where rn<>1
或者低于8版本的Mysql,您可以尝试以下
select * from
( SELECT
ur.user_id,
u.racid,
u.fname,
u.lname,
u.email,
u.last_login,
ur.role_id,
r.name AS role_name,
i.device_token AS ios,
dg.group_name,
dg.ad_group,
a.device_token AS android,
@row_number:=CASE
WHEN @user_id = ur.user_id and @racid = u.racid and @evicetoken = i.device_token THEN @row_number + 1
ELSE 1
END AS num,
@user_id :=ur.user_id, @racid = u.racid, @evicetoken = i.device_token
FROM
users AS u
LEFT OUTER JOIN
user_roles AS ur ON u.id = ur.user_id
LEFT OUTER JOIN
roles AS r ON ur.role_id = r.id
LEFT OUTER JOIN
ios_tokens AS i ON u.racid = i.racf_id
LEFT OUTER JOIN
android_tokens AS a ON u.racid = a.racf_id
LEFT OUTER JOIN
dashboard_groups AS dg ON dg.role_id = r.id,
(SELECT @user_id:=0,@racid=0,@evicetoken=0,@row_number:=0) as t
)X where num<>1
答案 1 :(得分:0)
这与删除重复的行无关,但是如果您需要单个表中多列的唯一性,则可以对多列使用唯一索引。如果不是,那么请忽略此内容。
ALTER TABLE `users` ADD UNIQUE `unique_index`(`col1`, `col2`, `col3`);
How do I specify unique constraint for multiple columns in MySQL?