简体   繁体   English

MySql搜索两个表并用like和%比较列

[英]MySql Searching two tables and comparing columns with like and %

I am trying to select data from two tables and insert it into another one. 我正在尝试从两个表中选择数据并将其插入到另一个表中。 I want to select the data when certain things match in each table. 当某些内容在每个表中匹配时,我想选择数据。 The problem is that one of the comparisons needs to be a like and I am at a loss. 问题是比较之一必须是相似的,我很茫然。 The sql statement is below and I believe that it will at least show what I am trying to do. sql语句在下面,我相信它至少会显示我正在尝试做的事情。

insert into hr_numbers 
  (`user_id`, `hr_number`) 
  select distinct u.user_id, t.num 
    from temp t, users u 
   where t.name like '%' + u.l_name + '%';

I have tried to use procedures but cannot figure that out or even tell if that would help. 我尝试使用过程,但无法弄清楚,甚至无法确定是否有帮助。

First, make sure the SELECT is returning what you want before attempting insertion. 首先,在尝试插入之前,请确保SELECT返回所需的内容。 This: 这个:

SELECT DISTINCT 
       u.user_id, 
       t.num 
  FROM temp t, users u 
 WHERE t.name like '%' + u.l_name + '%'

...is using ANSI-89 JOIN syntax. ...正在使用ANSI-89 JOIN语法。 ANSI-92 join syntax is a better choice: ANSI-92连接语法是更好的选择:

SELECT DISTINCT
       u.user_id,
       t.num
  FROM USERS u
  JOIN TEMP t ON t.name LIKE CONCAT('%', u.l_name ,'%')

...but the join criteria looks flawed. ...但是加入标准看起来有缺陷。 It's going to link rows were the last name appears in the t.name value, leading to the Smith problem: If the last name is "Smith", all rows will link up - even if the names are John, Jim, etc. 它将链接到t.name值中出现姓氏的行,从而导致Smith问题:如果姓氏是“ Smith”,则所有行都将链接起来-即使名字是John,Jim等。

Try this: 尝试这个:

INSERT INTO hr_numbers(`user_id`, `hr_number`)
SELECT DISTINCT U.user_id, T.num
FROM temp T
INNER JOIN users U ON T.NAME LIKE '%' + U.l_name + '%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM