使用多表SQL语句选择数据会返回意外结果

时间:2011-07-18 23:05:50

标签: mysql sql select csv export

我想格式化SQL结果,然后导出到CSV(phpMyAdmin导出)。

SQL语句:

SELECT
product.name,
features.text
FROM products as product, product_features as features
WHERE
features.product_id=products.id LIMIT 0,100

表格结构:

products

------------
id | name
------------
24   Baseball
25   Rope

product_features

--------------------------
id | text      | product_id
--------------------------
45   Leather..   24
46   Hardball    24
47   Nylon       25
48   Black       25

问题:我明白了:

Baseball Leather
Baseball Hardball
Rope Nylon
Rope Black

我很难用SQL语句解决什么类型的解决方案。

结果我正在寻找:

Baseball, Leather..., Hardball
Basketball, Nylon, Black

1 个答案:

答案 0 :(得分:1)

您需要某种类型的聚合:

SELECT product.name, GROUP_CONCAT(features.text)
FROM products JOIN product_features ON(products.id = product_features.product_id)
GROUP BY products.id;