【问题标题】:Selecting data with multi table SQL statement returns unexpected result使用多表 SQL 语句选择数据返回意外结果
【发布时间】:2011-07-18 23:05:50
【问题描述】:

我想格式化 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

【问题讨论】:

    标签: mysql sql select csv export


    【解决方案1】:

    您需要某种类型的聚合:

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

    【讨论】:

    • 完美!谢谢!我必须做的唯一改变是从“GROUP_BY”中删除_。
    • 糟糕,不知道它是怎么进来的——修复了! (顺便说一句,请随意接受或投票:-))
    • 不应该是GROUP BY product.name吗?
    • @Bohemian:不是真的。 ID 就是要匹配的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多