簡體   English   中英

在另一列中找到一個列的單詞並替換?

[英]Find a word of a column in another column and replace?

這是我第一次在這里發布! 希望得到一個很好的答復。

我有兩個表,根據需要在table1的名稱中查找並替換為''table2的名稱的路徑。

table1
+---------------+----------+
| name          | path     |
+---------------+----------+
| John Smith    | 12345    |
+---------------+----------+
| John Smith    | 54321    |
+---------------+----------+
| JohnSmith     | 12345    |
+---------------+----------+

table2
+---------------+----------+
| name          | path     |
+---------------+----------+
| John          | 12345    |
+---------------+----------+
| Smith         | 54321    |
+---------------+----------+

the final result would be like
+---------------+----------+
| name          | path     |
+---------------+----------+
| Smith         | 12345    |
+---------------+----------+
| John          | 54321    |
+---------------+----------+
| JohnSmith     | 12345    |
+---------------+----------+

如您所見,我只需要替換完全匹配。 所以在JohnSmith中,我不會刪除John。

問題還在於,是否僅使用mysql查詢即可? 或者像這樣的東西還需要一些PHP?

先感謝您。


這兩個查詢都很接近,但是沒有給出我需要的確切輸出。

例如第一個產品

NAME        PATH
Smith       12345
John        54321
Smith       12345

這里的最后一行,不應更改。 由於我們沒有完全匹配的內容。 並且該行應保持相同的“ JohnSmith”

在第二個中,輸出是

NAME        PATH
Smith       12345
John Smith  54321
JohnSmith   12345

這里的第二行似乎是錯誤的,因為它應該刪除“ Smith”

任何想法 ?

這已經很接近了,但是我承認您不了解您的最后情況-不是Smith / 12345嗎? 這使用REPLACE

SELECT REPLACE(t1.Name, t2.Name, '') Name, t1.Path
FROM Table1 t1
  LEFT JOIN Table2 t2 ON t1.path = t2.path

這是SQL Fiddle

- 編輯 -

這是使用CASE語句的嘗試。 它在中間,開頭或結尾進行檢查:

SELECT 
  CASE 
    WHEN t1.Name Like CONCAT('% ',IFNULL(t2.Name,''),' %')
    THEN REPLACE(t1.Name, CONCAT(' ',IFNULL(t2.Name,''),' '), ' ') 

    WHEN t1.Name Like CONCAT(IFNULL(t2.Name,''),' %')
    THEN REPLACE(t1.Name, CONCAT(IFNULL(t2.Name,''),' '), '') 

    WHEN t1.Name Like CONCAT('% ',IFNULL(t2.Name,''))
    THEN REPLACE(t1.Name, CONCAT(' ',IFNULL(t2.Name,''),' '), '') 

    ELSE
       t1.Name

END Name, t1.Path
FROM Table1 t1
  LEFT JOIN Table2 t2 ON t1.path = t2.path

還有更多的提琴

產生以下結果:

NAME        PATH
Smith       12345
John Smith  54321
JohnSmith   12345

這將完成工作:

SELECT 
    REPLACE(CONCAT(' ',t1.Name,' '), 
    CONCAT(' ',t2.Name,' '), '') Name, 
    t1.Path
FROM 
    Table1 t1
LEFT JOIN 
    Table2 t2 ON t1.path = t2.path

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM