我有一张像这样的表usercolor
:
id | idUser | color
-----------------------
1 | 1 | red
2 | 1 | blue
3 | 2 | green
4 | 2 | blue
5 | 3 | null
6 | 3 | blue
7 | 4 | null
我希望每个idUser
一个随机拟合颜色,尽可能不为空。像这样:
idUser | color
---------------
1 | blue
2 | green
3 | blue
4 | null
我以为我可以通过
来实现它SELECT idUser, color FROM usercolor GROUP BY idUser
但是,使用此SQL可能会发生idUser
3映射为null,尽管idUser
存在蓝色。我怎么能阻止这个?
答案 0 :(得分:1)
如果你想为每个用户提供一种随机颜色,那么就会想到一个相关的子查询:
select idUser,
(select uc.color
from usercolor uc
where uc.idUser = u.idUser and uc.color is not null
order by rand()
limit 1
) as color
from (select distinct idUser from usercolor) u -- you can use `users` here instead