mysql union和union all

 我来答
新科技17
2022-06-27 · TA获得超过5851个赞
知道小有建树答主
回答量:355
采纳率:100%
帮助的人:72.7万
展开全部

select * from aa;

select * from bb;

select * from aa union select * from bb;

如果想使用ORDER BY或LIMIT子句来对全部UNION结果进行分类或限制,则应对单个地SELECT语句加圆括号,并把ORDER BY或LIMIT放到最后一个的后面
(select uid,name from aa) union (select uid,name from bb)ORDER BY uid desc limit 10;两个SQL都得加上()。

select uid,name from (select uid,name from aa union select uid,name from bb) t order by uid desc LIMIT 10; 记得给 括号合并的表取上别名,否则报错 如下图

select uid,name from (select uid,name from aa union select uid,name from bb) order by uid desc LIMIT 10;没取别名 t 报错

select uid,group_concat(name )from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;

select uid,name from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;

运行上面那个SQL会报错,因为5.7版本之后的MYSQL不在group by里的字段 跟在select会报错解决办法是,用函数 any_value(字段名)

select any_value(name),max(uid)from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;
运行上面的SQL 不报错了

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式