Select an array per row?
I have 2 tables:
1. products
- pro开发者_JAVA技巧duct_id
- title
2. product_categories
- product_id
- category_id
Each product can have more than one category. I store this information in the product_categories table. I want to be able to SELECT all the category_ids when I select a product in 1 query. How can I do this? I have the following so far, but it will only select 1 category id:
SELECT
p.*,
(SELECT
category_id
FROM
product_categories
WHERE product_id = p.product_id) as category_ids
FROM
products AS p
You could use a left join, Group By, and GROUP_CONCAT
How to use GROUP BY to concatenate strings in MySQL?
SELECT products.*, GROUP_CONCAT(category_id SEPARATOR ' ')
FROM products LEFT JOIN product_categories
ON product_categories.product_id = products.product_id
GROUP BY product_id;
select products.*,product_categories from left outer join product_categories on product_categories.product_id = products.product_id
精彩评论