简体   繁体   中英

Sub Query Returns More Than 1 Row LIKE & CONCAT with Wildcards

I have 2 tables, 'contacts' and 'job_titles'. Within the 'contacts' table there is a field named 'position'. With the new 'job_titles' table, I want to update a field in the 'contacts' table called 'job_title_id' if the 'position' fields value is similar to the 'title' field in the 'job_titles' table and I've come across a snag.

Because the position field is a free text field we could have values like:

  • Service Delivery Manager of Such a Company

Also, we may have in the 'title' field of the 'job_titles' table values like:

  • Service Delivery Manager
  • IT Service Delivery Manager
  • Senior Service Delivery Manager

So when I run the following query, I am getting a 'Sub query returns more than 1 row' error.

UPDATE contacts 
SET job_title_id = 
  (SELECT id 
   FROM job_titles 
   WHERE job_titles.title LIKE CONCAT('%', contacts.position, '%')
  );

Is there a way I can run a wildcard query like above that will do what I need? Thanks.

The following will match the shortest title, on the assumption that is more generic:

UPDATE contacts c
    SET job_title_id = (SELECT id
                        FROM job_titles jt
                        WHERE jt.title LIKE CONCAT('%', c.position, '%')
                        ORDER BY char_length(jt.title)
                        LIMIT 1
                       );

Wildcards query may return more then one records. so the one solution can be if you use the nested query with limit 1.

Like

UPDATE contacts SET job_title_id = (SELECT id FROM job_titles WHERE job_titles.title LIKE CONCAT('%', contacts.position, '%') limit 1);

But here an issue can occur that it may return the records for senior service delivery for the search of service delivery, so if your field's data start with job title then you can write the query like.

UPDATE contacts SET job_title_id = (SELECT id FROM job_titles WHERE job_titles.title LIKE CONCAT(contacts.position, '%') limit 1);

This query will be helpful.

UPDATE A SET A.job_title_id = B.id FROM contacts AS A 
INNER JOIN job_titles AS B ON B.id IS Not NUll 
WHERE B.title LIKE CONCAT('%', A.position, '%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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