【问题标题】:mysql query concat not working as expectedmysql查询连接没有按预期工作
【发布时间】:2015-11-25 15:12:32
【问题描述】:

这是我的数据结构:

table: items
id   name         category1  category2  category3
--------------------------------------------------
1    apple        1          57         NULL
2    banana       1          41         55
3    orange       1          53         NULL
4    strawberry   1          NULL       NULL

想要的输出:

id   name         categories
--------------------------------------------------
1    apple        1,57
2    banana       1,41,55
3    orange       1,53
4    strawberry   1

这是我的查询:

SELECT items.*, CONCAT(category, ",", category2, ",", category3) AS categories FROM toom_items

有些东西不工作,我得到了这个:

id   name         categories
--------------------------------------------------
1    apple        NULL
2    banana       NULL
3    orange       NULL
4    strawberry   NULL

有什么想法吗?

【问题讨论】:

  • 我建议你使用concat_ws(),因为你只需要写一次分隔符,例如concat_ws(",", category, category2, category3)
  • 帮助了......谢谢!

标签: mysql concat


【解决方案1】:

我认为您在第一类中缺少“1”:像这样更新您的查询:

SELECT items.*, CONCAT(category1, ",", category2, ",", category3) AS categories FROM toom_items

或者请像这样使用连接:

CONCAT_WS(',', category1, category2, category3);

【讨论】:

    【解决方案2】:

    我在你的问题中发现了两处错误。

    首先,您的查询:

    SELECT items.*, CONCAT(category, ",", category2, ",", category3) AS categories FROM toom_items
    

    您应该参考表 items,因为在您给定的示例中,您没有 toom_items 表。

    其次,根据您的查询,您得到的结果与您的查询不匹配。由于您为字段选择items.*,因此它应该类似于:

    | id   | name       | category1 | category2 | category3 | categories |
    +------+------------+-----------+-----------+-----------+------------+
    |    1 | apple      |         1 |        57 |      NULL | NULL       |
    |    2 | banana     |         1 |        41 |        55 | NULL       |
    |    3 | orange     |         1 |        53 |      NULL | NULL       |
    |    4 | strawberry |         1 |      NULL |      NULL | NULL       |
    

    为了回答这个问题,我已经尝试了你的结构,正确的查询应该是:

    SELECT id, name, CONCAT_WS(',', category1, category2, category3) as 'categories' FROM items;
    

    结果将是:

    +------+------------+------------+
    | id   | name       | categories |
    +------+------------+------------+
    |    1 | apple      | 1,57       |
    |    2 | banana     | 1,41,55    |
    |    3 | orange     | 1,53       |
    |    4 | strawberry | 1          |
    +------+------------+------------+
    

    参考截图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多