資料表儲存多id字串,靈活sql由行轉列

2021-07-30 11:01:31 字數 1568 閱讀 9842

一對多沒有建立中間表的時候經常會採用分隔符的形式將「多」儲存在「一」的乙個欄位裡,這樣做的代價是無法像一對多的時候那樣直接關聯查詢,一般採用在程式中分割後分別查詢的辦法。如下圖:

如何才能直接用sql語句查詢出下圖的效果呢?

可以借助乙個序號表,該表中除了連續的id沒有其它字段,id的值範圍取決於"一"中儲存的資訊拆分後的數量。

實現sql:

[sql]view plain

copy

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 

assize

from

`user

`  )b on

a.id <= b.

size

[sql]

select  

mid,  

replace(  

substring_index(group_id, ',', a.id),  

concat(  

substring_index(group_id, ',', a.id - 1),  

','  

),  

''  

)as group_id  

from  

(select id from rims_basic_area where id <20) a  

cross join(  

select  

id as mid,  

concat(group_id, ',')as group_id,  

length(group_id)- length(replace(group_id, ',', ''))+ 1 as size  

from  

`rims_message_push_setting`  

)b on a.id <= b.size

逗號分割字串經儲存過程存入資料表中

前端提交一串逗號分割的字串,經儲存過程,存入sql資料表中。表如下 準備儲存過程 上面 43行 有乙個自定義函式,它是把逗號分割的字串轉為xml格式。參考 符號分割的字串轉換為xml 舉個例子 金,水,木,火,土 execute dbo usp miscellaneous insert str se...

MySQL資料表儲存特殊字元

1.應用場景 有時,需要向資料庫中儲存一些特殊字元,需要先進行特殊處理,如轉義處理等,避免資料儲存出錯。2.學習 操作 環境 mysql mariadb 具體版本號沒記住,也是較新的版本 2.1.向資料表中插入如下資料 insert into mc common info path version ...

Mysql儲存大資料字串

使用text mysql提供四種text型別 tinytext,text,mediumtext和longtext。下面顯示每個text型別的大小,假設我們使用乙個字符集,該字符集需要1個位元組來儲存字元。tinytext可以儲存的最大字元是255 2 8 256,1位元組開銷 請參閱以下示例 cre...