2016-08-25 35 views
-2

假設我有兩行兩列的MySQL表。如何查找逗號分隔數組中兩個數字之間的差異?

Column 1 = ID 
Column 2 = NUMBERS 

NUMBERS首先在現場排第二&排有以下逗號分隔值:

NUMBERS(Row 1) = 1,2,3,4,5,6,7,8 
NUMBERS(Row 2) = 6,7,8,9,10,11 

現在,我要找到所有這些都是1 & 11之間。我已經嘗試了MYSQL BETWEEN功能數字,但它沒有返回想要的結果。

有沒有我可以得到想要的結果的方法嗎?

+1

經過此[鏈接](http://stackoverflow.com/questions/11835155/mysql-split-comma-separated-string-into-temp-table) 由於MySQL是不與分割字符串功能捆綁在一起,你必須自己做。一旦你已經分裂的數量,然後使用BETWEEN子句來從在例如上面的鏈接 –

+0

一種方式創建臨時表所需的結果:顯示所有的計算:http://sqlfiddle.com/#!9/cfea18/6。說明:[我可以用純粹的mysql解決這個問題嗎? (加盟上「;」在一列分隔值)](http://stackoverflow.com/a/33806675/3184785) –

+1

現在你知道,你不能使用關係數據庫爲文本文件,你不?你在SQL中創建行,你不用逗號分隔數據,這不是javascript。 – Mjh

回答

0

經與序列號中的表像

sequence_numbers

number 
    1 
    2 
    .. 
    100 

,你可以從你的列表中使用JOIN提取數字和FIND_IN_SET()函數

select t.ID, s.number 
from mytable t 
join sequence_numbers s 
    on find_in_set(s.number, t.NUMBERS) 

結果:

| ID | number | 
|----|--------| 
| 1 |  1 | 
| 1 |  2 | 
| 1 |  3 | 
| 1 |  4 | 
| 1 |  5 | 
| 1 |  6 | 
| 2 |  6 | 
| 1 |  7 | 
| 2 |  7 | 
| 1 |  8 | 
| 2 |  8 | 
| 2 |  9 | 
| 2 |  10 | 
| 2 |  11 | 

http://sqlfiddle.com/#!9/b4144/4

現在很多任務都是與結果更加簡單。

限於數字從3至7:

select t.ID, s.number 
from mytable t 
join sequence_numbers s 
    on find_in_set(s.number, t.NUMBERS) 
where s.number between 3 and 7 

結果:

| ID | number | 
|----|--------| 
| 1 |  3 | 
| 1 |  4 | 
| 1 |  5 | 
| 1 |  6 | 
| 2 |  6 | 
| 1 |  7 | 
| 2 |  7 | 

http://sqlfiddle.com/#!9/b4144/3

一個簡單的方法來建立一個大序列表是使用內部columns表(或用足夠的行任何表)與自身加入它:

create table sequence_numbers (number int auto_increment primary key) 
    select null as number 
    from information_schema.columns c1 
    cross join information_schema.columns c2 
    limit 1000000 
; 

http://sqlfiddle.com/#!9/7cc0a/2

相關問題