简体   繁体   中英

How can I find all rows whose string value appears in a column of another table?

I have table X with a string column Y. It might contain values such as "Hi", "Blue", "Red", "great", etc. I have another table, A, with a string column B. It might contain values such as "Hi everyone", "The sky is blue and roses are red.".

I want to list all values in table X where the value is contained inside the value of Table A's Column B. For example, in the above, "Blue", "Hi", and "Red" should be returned as "Hi everyone" contains "Hi". The second value, "The sky is blue and roses are red" contains both "Red" and "Blue". "Great" would not be displayed because it is not in any value of Column B.

I've tried using LIKE but it doesn't seem to work with select (select Y where Y in like concat('%', select B from A, '%'))

You could get your desired results using following approaches

Join

SELECT tx.*
FROM tablex tx
JOIN tablea ta ON ta.columnB LIKE CONCAT('%', tx.columnY, '%')

Exists

SELECT *
FROM tablex tx
WHERE EXISTS (
    SELECT 1
    FROM tablea
    WHERE columnB LIKE CONCAT('%', tx.columnY, '%')
)

Demo

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