Php SQL连接多个ID
第一桌Php SQL连接多个ID,php,mysql,sql,join,Php,Mysql,Sql,Join,第一桌 |product_name | category_ids | |---------------------------------| |- apple | 1, 2 | |- extra_apple | 1, 3 | 第二桌 |category_id | category_name | |---------------------------------| |- 1 | fruit
|product_name | category_ids |
|---------------------------------|
|- apple | 1, 2 |
|- extra_apple | 1, 3 |
第二桌
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
我怎么能加入这个,所以我得到了这样的东西
| product_name | category_names |
--------------------------------------------
| apple | fruit, cheap |
| extra_apple | fruit, expensive |
要使其正确,请添加另一个表:
product_categories table
------------------------
product_id
category_id
它包含一个产品的每个类别的一条记录。要使其正确,请添加另一个表:
product_categories table
------------------------
product_id
category_id
它为产品的每个类别都包含一条记录。第一个表不规范化
|product_name | category_ids |
|---------------------------------|
|- apple | 1, 2 |
|- extra_apple | 1, 3 |
首先将此表规范化为
|product_name | category_ids |
|---------------------------------|
|- apple | 1 |
|- apple | 2 |
|- extra_apple | 1 |
|- extra_apple | 3 |
第二桌
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
MySQL语法为:从第一个表中选择T1.product\u name、T2.category\u name作为T1,从第二个表中选择T2,其中T1.category\u id=T2.category\u id
这将为您提供以下结果:
| product_name | category_names |
--------------------------------------------
| apple | fruit |
| apple | cheap |
| extra_apple | fruit |
| extra_apple | expensive |
第一个表不是规范化的
|product_name | category_ids |
|---------------------------------|
|- apple | 1, 2 |
|- extra_apple | 1, 3 |
首先将此表规范化为
|product_name | category_ids |
|---------------------------------|
|- apple | 1 |
|- apple | 2 |
|- extra_apple | 1 |
|- extra_apple | 3 |
第二桌
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
|category_id | category_name |
|---------------------------------|
|- 1 | fruit |
|- 2 | cheap |
|- 3 | expensive |
MySQL语法为:从第一个表中选择T1.product\u name、T2.category\u name作为T1,从第二个表中选择T2,其中T1.category\u id=T2.category\u id
这将为您提供以下结果:
| product_name | category_names |
--------------------------------------------
| apple | fruit |
| apple | cheap |
| extra_apple | fruit |
| extra_apple | expensive |
这里真正的解决方案是修复未规范化的表设计。这里真正的解决方案是修复未规范化的表设计。