首页 > 解决方案 > 在mysql联合查询中插入序列号

问题描述

我正在使用联合作为 mysql 查询

(Select id,c1,c2,c3 from table where c1=x1 and c2=x2 ) union  <<---block 1
(Select id,c1,c2,c3 from table where c1=x1 and c2=x2 ) union  <<---block 2
...
(Select id,c1,c2,c3 from table where c1=x1 and c2=x2 ) union  <<---block mth

返回result

id|c1|c2|c3
------------
1 |..|..|..
2 |..|..|..
3 |..|..|..

.. .. .. ..
.. .. .. ..
nth.. .. ..

我想要添加一个 no 的表,显示结果是从哪个联合块获得的

id|c1|c2|c3|blk
---------------
1 |..|..|..|1
2 |..|..|..|1
3 |..|..|..|2

.. .. .. ..|3
.. .. .. ..|3
nth.. .. ..|3

标签: mysqlrdbms

解决方案


使用 blk 编号向每个查询添加 1 列:

(Select id,c1,c2,c3, 1 blk from table where c1=x1 and c2=x2 )
(Select id,c1,c2,c3, 2 from table where c1=x1 and c2=x2 ) 
...
(Select id,c1,c2,c3, <n> from table where c1=x1 and c2=x2 )

推荐阅读