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.
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.
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
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.
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.