对union使用order by或limit
l 如果您想使用ORDER BY或LIMIT子句来对全部UNION结果进行分类或限制,则应对单个地SELECT语句加圆括号,并把ORDER BY或LIMIT放到最后一个的后面。
例如:
(SELECT a FROM tbl_name WHERE a=10 AND B=1)
UNION
(SELECT a FROM tbl_name WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
麻烦一点也可以这么干:
select userid from
(select userid from testa
union all
select userid from testb) t
order by userid limit 0,1;
-- 如果你还想group by,而且还有条件,那么:
select userid from
(select userid from testa
union all
select userid from testb) t
group by userid having count(userid) = 2;
--注意:from的表必须有名字,如果是子查询就要有别名
区分多表
专门做一个字段,即可区分别名。例如:
select posts_id,posts_name,'users' as table_name from yy_posts
UNION
select user_id,user_nickname,'posts' as table_name from yy_user