简体   繁体   中英

How to find records in table based on another table's id field in MySQL?

I have in my companies table this rows:

+----+-------------+--------------+
| id | name        | city         |
+----+-------------+--------------+
| 1  | MY Company  | New York     |
| 2  | SampleComp  | Washington   |
| 3  | TestCompany |              |
| 4  | Your Inc.   |              |
+----+-------------+--------------+

In the discount_filters table are these rows:

+----+-------------+--------------+
| id | name        | city         |
+----+-------------+--------------+
| 10 |             | New          |
| 20 |             | York         |
| 30 | Sample      |              |
+----+-------------+--------------+

In the moment of search I know only the id of the company.

How can I found all records from discount_filters which match to my companies.id ? In the database are more than 10.000 companies and more than 1000 discount filters. There are many columns in both table.

If the companies.id is 1 I want to get back the discount_filters with id 10 and 20 .

If the companies.id is 2 I want to get back the discount_filters with id 30 .

If the companies.id is 4 I don't want to get back anything.

Is there any reverse select logic in SQL?

You can put some conditional logic in the join conditions:

select c.*, d.name, d.city
from companies c
inner join discount_filters df
    on c.name like concat('%', df.name, '%')
    or c.city like concat('%', df.city, '%')

Note, however, that this is a very inefficient way to proceed. The conditional logic along with string functions and pattern matching precludes the use of existing indexes. You would better off put effort into fixing the data in the discount_filters table, so you can do a proper join with a straight index lookup.

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