我有两张桌子:
1. products
- product_id
- title
2. product_categories
- product_id
- category_id
每种产品可以有多个类别。我将此信息存储在product_categories表中。我希望能够在1个查询中选择产品时选择所有category_ids。我怎样才能做到这一点?到目前为止我有以下内容,但它只会选择1个类别ID:
SELECT
p.*,
(SELECT
category_id
FROM
product_categories
WHERE product_id = p.product_id) as category_ids
FROM
products AS p
答案 0 :(得分:0)
选择产品。*,product_categories来自 product_categories.product_id = products.product_id
左外连接product_categories答案 1 :(得分:0)
您可以使用左连接,分组依据和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;