0

这是我第一次在这里发帖!希望能得到好的答复。

我有两个表,根据我需要找到的路径,将 table2 的名称替换为 table1 的名称。

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”

任何想法 ?

4

2 回答 2

0

这很接近,但我承认我不明白你的最后一个条件——不应该是 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
于 2013-02-17T14:57:39.253 回答
0

这将完成这项工作:

SELECT 
    REPLACE(CONCAT(' ',t1.Name,' '), 
    CONCAT(' ',t2.Name,' '), '') Name, 
    t1.Path
FROM 
    Table1 t1
LEFT JOIN 
    Table2 t2 ON t1.path = t2.path
于 2013-02-18T11:32:17.623 回答