如何使用LIKE语句

时间:2017-03-10 08:18:44

标签: mysql sql sql-server

如何从两个表中获取匹配的记录

匹配表

CREATE TABLE matching (
  ID INT,
  Name varchar(20)
);

INSERT INTO matching(ID,name) VALUES (1,'Child'),(2,'GrandChild'),(3,'parent')

TreeMatching

CREATE TABLE Treematching (
  ID INT,
  Name varchar(20)
);

INSERT INTO Treematching(ID,name) VALUES 
(1,'Child-Foster'),
(2,'Child-Filly'),
(3,'Child-Ricky'),
(4,'GRandchild-Filmy'),
(5,'GRandchild-Freaky'),
(6,'GRandchild-Frim'),
(7,'Frim'),
(8,'None'),
(9,'parent-John')

如何从树匹配表中获取匹配记录

输出

ID  Name              TName
1   Child           Child-Foster
2   Child           Child-Filly
3   Child           Child-Ricky
4   GRandchild      GRandchild-Filmy
5   GRandchild      GRandchild-Freaky
6   GRandchild      GRandchild-Frim
9   parent          parent-John

如何使用我尝试过使用CONCAT的类似语句来获取相同的记录。

4 个答案:

答案 0 :(得分:1)

如果您使用SQL Server,可以尝试这样的事情:

SELECT 
    t.ID,
    m.Name,
    t.Name
FROM matching AS m
INNER JOIN Treematching AS t
ON t.Name LIKE '%'+m.Name+'%'

如果你使用MySQL服务器试试这个:

SELECT 
    t.ID,
    m.Name,
    t.Name
FROM matching  AS m
INNER JOIN Treematching AS t
ON t.Name LIKE CONCAT('%',m.Name,'%')

关于MySQL版本,请查看以下链接。

sqlfiddle

答案 1 :(得分:0)

你可能会做这样的事情(没有经过测试,我没有sql-server实例):

SELECT M.Id, M.Name, T.Name 
  FROM matching AS M
       INNER JOIN Treematching AS T
          ON M.Name LIKE T.Name + '%';

答案 2 :(得分:0)

尝试以下查询,

SELECT  TM.ID,M.Name,TM.Name
FROM    @matching   AS  M
    INNER JOIN  @Treematching   AS  TM  ON  TM.Name LIKE M.Name+'%'

答案 3 :(得分:0)

tcp6       0      0 :::61616                :::*                    LISTEN      26503/docker-proxy   off (0.00/0/0)    
tcp6       0      0 :::8090                 :::*                    LISTEN      26511/docker-proxy   off (0.00/0/0)
tcp6       0      0 :::8091                 :::*                    LISTEN      26519/docker-proxy   off (0.00/0/0)