简体   繁体   中英

How to JOIN tables in many-to-many relationship

I have a table named category which has fields and fields has field options

category->fields->fields_options

I've created a table cat_fields

┏━━━━┳━━━━━━━━┳━━━━━━━━━━┓
┃ id ┃ cat_id ┃ field_id ┃
┣━━━━╋━━━━━━━━╋━━━━━━━━━━┫
┃ 0  ┃ 1      ┃ 2        ┃
┣━━━━╋━━━━━━━━╋━━━━━━━━━━┫
┃ 1  ┃ 1      ┃ 1        ┃
┗━━━━┻━━━━━━━━┻━━━━━━━━━━┛

Now I need this table to get results from category so that I can have all the fields related to category and all the options related to the fields of that category.

Is it possible to get all that in one go?

You didn't show the layout of the other two tables, but presuming each has an ID field, the following should work:

SELECT *
FROM `category`
JOIN `fields`
ON `fields`.`field_id` = `category`.`field_id`
JOIN `field_options`
ON `field_options`.`field_id` = `fields`.`field_id`

Adjust to use the actual column names and table names.

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