简体   繁体   English

比较不同表中的两列

[英]Compare two columns from different tables

I know that this question has been asked several times and I did read them all. 我知道这个问题已经问过几次了,我确实读了全部。 However, my situation is little different I can still can't get the right results with my SQL statement below. 但是,我的情况几乎没有什么不同,我仍然无法通过下面的SQL语句获得正确的结果。

I have two tables as shown below: 我有两个表,如下所示:

TABLE A
######################################################################
   |   ID   | IP_Address    | Username  | Comments
----------------------------------------------------------------------  
    1       128.        abc     travel to US
    2       127.        dzd     author
    3       127.        abc     It's not redundant at all. Not offering a single function
    4       124.        deb     I just lost laptop.  How do I report it?
-----------------------------------------------------------------------



TABLE B
######################################################################
   |   keywords     |
----------------------------------------------------------------------  
    author
    How do I report
-----------------------------------------------------------------------

My intention is to pull out all records in TABLE A when the Comments column partially matches one of the keywords in TABLE B. 我的意图是在“注释”列部分匹配表B中的关键字之一时,提取表A中的所有记录。

Here is the query: 这是查询:

SELECT ID, IP_Address, UserName, Comments FROM TABLEA
FULL JOIN TABLEB
ON TABLEA.Comments LIKE TABLEB.Keywords
WHERE TABLEA.Comments IS NOT NULL AND TABLEB.Keywords IS NOT NULL

It works but it only pulls out the EXACT match, not a part of the comments. 它可以工作,但只提取完全匹配项,而不是注释的一部分。
In my sample, it pulls out "author" record but not "I just lost laptop. How do I report it?" 在我的示例中,它提取的是“作者”记录,而不是“我只是丢失了笔记本电脑。如何报告?” record. 记录。

Is there a way to twist my query to meet my requirements? 有没有一种方法可以扭曲我的查询以满足我的要求?

Thanks 谢谢

JPL 联合警察

Add % to the LIKE clause 在LIKE子句中添加%

SELECT ID, IP_Address, UserName, Comments FROM TABLEA
FULL JOIN TABLEB
ON TABLEA.Comments LIKE '%' + TABLEB.Keywords + '%'
WHERE TABLEA.Comments IS NOT NULL AND TABLEB.Keywords IS NOT NULL

This will do what you need. 这将满足您的需求。

SELECT ID, IP_Address, UserName
FROM TABLE1 T1
CROSS APPLY (SELECT Keywords FROM Table2) T2
WHERE CHARINDEX(T2.Keywords,T1.Comments) >0

The CROSS APPLY could be replaced with the full join, but cross apply works better if there are more columns in the 2nd table. 可以将CROSS APPLY替换为完全联接,但是如果第二个表中有更多列,则交叉应用的效果会更好。

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

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