原来我是将distinct和order by一起使用,但是发现运行报错:
SQL_ERROR_INFO: "Expression #1of ORDER BY clause is not in SELECT list,
references column 'm.id'which is not in SELECT list; thisis incompatible with DISTINCT"
查了一下,发现这是因为先执行distinct去重产生虚拟表,在此虚拟表的基础上进行order by,由于虚拟表没有order by的字段,产生报错
也就是order by的字段必须在select中出现
原代码如下:
select distinct music_name
from follow t1 join music_likes t2 on follower_id=t2.user_id
join music t3 on t2.music_id=t3.id
where  t1.user_id=1 and t3.music_name not in (
select music_name
from music_likes t2 join music t3 on t2.music_id=t3.id
where t2.user_id=1)
order by t2.music_id
由于报错,用group by替代distinct:
select music_name
from follow t1 join music_likes t2 on follower_id=t2.user_id
join music t3 on t2.music_id=t3.id
where  t1.user_id=1 and t3.music_name not in (
select music_name
from music_likes t2 join music t3 on t2.music_id=t3.id
where t2.user_id=1)
group by t2.music_id
order by t2.music_id
如果一定要用distinct也可以这么写:
select music_name
from (
select distinct music_name,id
from follow t1 join music_likes t2 on follower_id=t2.user_id
join music t3 on t2.music_id=t3.id
where t1.user_id=1) t4
where t4.music_name not in (
select music_name
from music_likes t2 join music t3 on t2.music_id=t3.id
where t2.user_id=1)
order by t4.id