2017-02-11 66 views
1

第一个表SQL加入多个ID的

|product_name | category_ids | 
|---------------------------------| 
|- apple  | 1, 2   | 
|- extra_apple | 1, 3   | 

二表

|category_id | category_name | 
|---------------------------------| 
|- 1   | fruit   | 
|- 2   | cheap   | 
|- 3   | expensive  | 

我怎样才能加入这个,所以我得到这样的事情

|  product_name |  category_names | 
-------------------------------------------- 
|  apple   |  fruit, cheap  | 
|  extra_apple |  fruit, expensive | 
+2

这里真正的解决方法是修复你的不规范化的表设计。 –

回答

3

要正确添加另一个表格:

product_categories table 
------------------------ 
product_id 
category_id 

它包含产品所具有的每个类别的一条记录。

1

第一个表是不归

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

MySQL的语法为:“选择T1.product_name,T2.category_name FROM FIRST_TABLE AS T1,SECOND_TABLE AS T2 WHERE T1.category_ids = T2.category_id“

这会给你结果为:

|  product_name |  category_names | 
-------------------------------------------- 
|  apple   |  fruit   | 
|  apple   |  cheap   | 
|  extra_apple |  fruit   | 
|  extra_apple |  expensive  |