简体   繁体   中英

MySQL select from two column table

i have a table with only 2 columns. for example

table product.combinations
Column 1: product.id
Column 2: attribute.id

Product.id is unique every product can have 1 or more attributes. Products without attributes are not in the table

for example

table product.combinations

product.id | attribute.id

  1    |     1      |
  1    |     2      |
  2    |     1      |
  2    |     2      |
  5    |     1      |
  5    |     3      |
  9    |     2      |
  9    |     3      |
  9    |     5      |

Now i would like to do a select with the result below

product.id | attribute1 | attribute2 | attribute3 |attribute 4 | attribute 5

  1    |     1      |    2       |            |            |
  2    |     1      |    2       |            |            |
  5    |     1      |    3       |            |            |
  9    |     2      |    3       |     5      |            |

i have already tried with a pivot but i was not able to hae o good result. Can anyone give me a help?

First: DO NOT use dots/periods in table/column names, this won't work, use underscores instead.

Second, if it is ok to have all attribute ids in a comma-separated list, you can do the following (using MySQL's GROUP_CONCAT function):

mysql> SELECT
    -> product_id, GROUP_CONCAT(attribute_id ORDER BY attribute_id) AS attributes
    -> FROM product_combinations
    -> GROUP BY product_id
    -> ORDER BY product_id;
+------------+---------------+
| product_id | attributes    |
+------------+---------------+
|          1 | 1,2           |
|          2 | 1,2           |
|          5 | 1,3           |
|          9 | 2,3,5         |
+------------+---------------+
4 rows in set (0.00 sec)

从组合中选择属性UNION ALL从组合中选择属性

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