2013-02-28 115 views
1

在sql中,我想獲得所有的行,其中斜槓'/'作爲字符只存在一次。SQL選擇一個獨特的字符

對於exapmle:

[table1] 
id | path_name | 
1 | "/abc/def/"| 
2 | "/abc"  | 
3 | "https://stackoverflow.com/a/b/cdfe"| 
4 | "/hello" | 

select * from table1 where path_name=.... ; 

所以在這個例子,我想有隻第二和第四行......

如何做我必須成立這種說法?

+0

什麼口味SQL的? – 2013-02-28 12:21:17

+0

使用像'%/%'而不是'%/%/%' – Sachin 2013-02-28 12:22:25

回答

1

爲了找到表達式正好與一個斜線:

where path_name like '%/%' and not path_name like '%/%/%' 

說明:第一個檢查該斜線出現至少一次。第二個檢查它沒有出現兩次。

至少一次,但少於兩次只是一次。

如果您只想要以斜線開頭的那些,則應該將第一個圖案更改爲'/%'

3
where path_name like '%/%' and path_name not like '%/%/%' 

where len(path_name) = len(replace(path_name,'/','')) + 1 
0
select * from table1 where path_name not like '/%/%' and path_name not like '/%/'; 
0
1.select * from Table1 where len(path_name)-len(replace(path_name,'/',''))= 1 

2.select * from table1 where len(path_name)= len(replace(path_name,'/',''))+1 

3.select * from table1 where path_name like '%/%' and path_name not like'%/%/%' 
+1

請至少解釋一下你的答案。 – xpy 2017-10-17 08:53:25

+0

len(path_name)-len(replace(path_name,'/',''))-----這個語句長度是1個示例視圖@why我只需要一個'/'... 1.首先我找到長度然後我 - (減)替換/文字記錄器的長度 – 2017-10-17 11:12:21

+1

謝謝你的代碼片段,這可能會提供一些有限的即時幫助。通過展示*爲什麼*這是一個很好的解決方案,並且使它對未來的讀者更有用,一個正確的解釋[將大大提高](// meta.stackexchange.com/q/114762)其長期價值其他類似的問題。請[編輯]你的答案以添加一些解釋,包括你所做的假設。您應該提及一些有關效率的內容,以及可能會提高效率的任何索引。 – 2017-10-17 12:26:25