how to use a like with a join in sql?

后端 未结 5 1279
无人及你
无人及你 2020-11-30 23:27

I have 2 tables, say table A and table B and I want to perform a join, but the matching condition has to be where a column from A \'is like\' a column from B meaning that an

5条回答
  •  情书的邮戳
    2020-12-01 00:15

    In MySQL you could try:

    SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');

    Of course this would be a massively inefficient query because it would do a full table scan.

    Update: Here's a proof

    
    create table A (MYCOL varchar(255));
    create table B (MYCOL varchar(255));
    insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
    insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
    insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
    SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
    +-------+------------------+
    | MYCOL | MYCOL            |
    +-------+------------------+
    | foo   | fooblah          |
    | foo   | somethingfooblah |
    | foo   | foo              |
    | bar   | barblah          |
    | bar   | somethingbarblah |
    | bar   | bar              |
    +-------+------------------+
    6 rows in set (0.38 sec)
    

提交回复
热议问题