Home > Database > Mysql Tutorial > MySQL用数字辅助表实现复杂的列变行_MySQL

MySQL用数字辅助表实现复杂的列变行_MySQL

WBOY
Release: 2016-06-01 13:31:35
Original
1142 people have browsed it

bitsCN.com

MySQL用数字辅助表实现复杂的列变行

 

某天,QQ上一个圈子内的网友发来一个求助信息 :

PropID name   Amount3      元宝   22      乐豆   3
Copy after login

能否用一条sql 写成输出,就是复制对应Amount 的条数 :

PropID name3      元宝3      元宝2      乐豆2      乐豆2      乐豆
Copy after login

研究了下,用普通的group by sum if case when之类的搞不定,得换种思路,一时hang住了,就与网友Mr.W说起,他提供了数字辅助表的思路。

OK,搞定了,SQL如下:

select t1.propid,t1.name from tb t1,(select 1 as num union select 2 as num union select 3 as num ) t2 where t1.amount>= t2.num order by 1; 
Copy after login

MySQL用数字辅助表实现复杂的列变行_MySQL

中间的,

(select 1 as num union select 2 as num union select 3 as num ) t2
Copy after login
部分

最好你另外建一个num单列辅助表表,从1自增到N,给个几万就好,然后关联查方便一些自连接的sql判断,select貌似也没循环生成数字的功能。如下表nums


MySQL用数字辅助表实现复杂的列变行_MySQL
 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template