2016-01-23 99 views
0

我有一個表像這樣的:如何在mysql中創建子查詢?

|col1   |id | 
-------------------- 
|_22_1_565_18_|1 | 
|_22_1_18_ |2 | 
|_77_18_  |3 | 
|_22_1_55_45 |4 | 
|_18_1_65_13_ |5 | 
|_782_8_  |6 | 
|_782_1_8_21_ |7 | 
|_72_1_8_21_ |8 | 
|_782_8_251_ |9 | 
|_22_4_1_  |10 | 
|_77_1_5_21_ |11 | 
|_5_6_7_  |12 | 

col1中總是包含由「_」字符分隔的數字(一個接一個,一個,你看之前)。我需要編寫一個查詢:

1)要選擇包含字符串 「」(在這種情況下,所有行的行1,2,3,5)

2)要了解串序列是在「」 choosen行2最常見的(在「」這種情況下和「」的字符串)

3)向選擇不包含字符串「的所有行「但包含共同字符串」「和」 「(在這種情況下,行4,10)

4)要添加到所選擇的行中的那些接近它們的id接近性,特別是2行之後和2行之前,總是排除包含「」(在這種情況下,行6,8,9,11,12)的那些行

在這種情況下,查詢的最終結果是第4,10,6,8,9,11,12行。

我知道這很難,但是,我該怎麼辦?

+0

如果你有SQL腳本,然後分享它,我們將進行查詢,以測試這個 –

+0

第一家專賣店在'逗號separated'形式的數據。不使用'_'和你試過的東西?我們不在這裏做第一個查詢 –

+0

:'select * from table1 where find_in_set('18',replace(col1,'_',','))> 0' –

回答

1

1)

select * from table 
where col1 like '%_18_%' 

2)

select * from table 
where col1 like '%_22_%' and col1 like '%_1_%' 

3)

select * from table 
where col1 not like '%_18_%' 
and (col1 like '%_22_%' and col1 like '%_1_%') 

4)

select * from table 
where col1 not like '%_18_%' 
or (col1 not like '%_22_%' and col1 not like '%_1_%')