Home  >  Article  >  Database  >  mysql行转列(拆分字符串场景)_MySQL

mysql行转列(拆分字符串场景)_MySQL

WBOY
WBOYOriginal
2016-06-01 12:59:541036browse

一对多没有建立中间表的时候经常会采用分隔符的形式将“多”存储在“一”的一个字段里,这样做的代价是无法向一对多的时候那样直接关联查询,一般采用在程序中分割后分别查询的办法。如下图:

\

如何才能直接用sql语句查询出下图的效果呢?

\

可以借助一个序号表,该表中除了连续的id没有其它字段,id的值范围取决于"一"中存储的信息拆分后的数量。

\

实现sql:

 

SELECT
	NAME,
	REPLACE(
		SUBSTRING_INDEX(mobile, ',', a.id),
		CONCAT(
			SUBSTRING_INDEX(mobile, ',', a.id - 1),
			','
		),
		''
	)AS mobile
FROM
	squence a
CROSS JOIN(
	SELECT
		NAME,
		CONCAT(mobile, ',')AS mobile,
		LENGTH(mobile)- LENGTH(REPLACE(mobile, ',', ''))+ 1 AS size
	FROM
		`user`
)b ON a.id <= b.size

Statement:
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