简体   繁体   English

匹配两个表中的记录

[英]Matching records from two tables

I have two Tables: ads_info and ads.我有两个表:ads_info 和 ads。

I want to match records from two tables.我想匹配两个表中的记录。

SQL Schema for ads: SQL 广告架构:

| id |                 title |
|----|-----------------------|
|  1 | This Dog is very nice |

SQL Schema for ads_info: ads_info 的 SQL 架构:

| id |                     infotext |       tag |
|----|------------------------------|-----------|
|  1 | Dogs can eat a lot of things | dog, pets |

I want to check if the title of the Ads with id 1 has tags in ads_info.我想检查 id 为 1 的广告的标题是否在 ads_info 中有标签。 I have tried this:我试过这个:

SELECT * FROM `ads` where id = '1' UNION
SELECT * FROM `ads_info` where tag like '%ads.title%'

HERE IS SQL FIDDLE: LINK这里是 SQL 小提琴:链接

Do you want a simple join ?你想要一个简单的join吗?

select a.*, ai.tag,
       (tag like concat('%', ads.title, '%')) as flag
from ads a join
     ads_info ai
     on ai.id = a.id;

The flag is, of course, false. flag当然是假的。 It is rather hard to see situations where it would evaluate to true as you have expressed the logic.正如您所表达的逻辑,很难看到它会评估为真的情况。

Well you can do it this way: DEMO I am sure there are better ways and even this example can be better executed:) But it will maybe help...那么你可以这样做: DEMO我相信有更好的方法,甚至这个例子也可以更好地执行:) 但它可能会有所帮助......

First you create function for split and procedure for inserting those values in table(I have used here a answer from here LINK and corrected some small errors):首先,您创建 function 用于拆分和将这些值插入表中的过程(我在这里使用了来自此处LINK的答案并纠正了一些小错误):

FUNCTION FUNCTION

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

PROCEDURE程序

CREATE PROCEDURE ABC(in fullstr VARCHAR(255))

BEGIN

DECLARE a int default 0;
DECLARE str VARCHAR(255);

      simple_loop: LOOP
         SET a=a+1;
         SET str=SPLIT_STR(fullstr,",",a);
         IF str='' THEN
            LEAVE simple_loop;
         END IF;

         insert into my_temp_table values (str);
      END LOOP simple_loop;
END;

I have created a table for this values:我为此值创建了一个表:

create table my_temp_table (temp_columns varchar(100));

Called the procedure:调用过程:

 call ABC((select tag from ads_info));

And then you can use this:然后你可以使用这个:

Select * from ads B where exists
(select * from my_temp_table where 
find_in_set(UPPER(trim(temp_columns)), replace(UPPER(B.TITLE), ' ', ',')) > 0 );

Or this:或这个:

SELECT * FROM ads, my_temp_table
WHERE find_in_set(UPPER(trim(temp_columns)), replace(UPPER(ads.TITLE), ' ', ',')) > 0 ;

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

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