mysql查询concat没有按预期工作

时间:2015-11-25 15:12:33

标签: mysql concat

这是我的数据结构:

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

任何想法有什么不对?

2 个答案:

答案 0 :(得分:0)

我认为你错过了#34; 1"从第一类:更新您的查询:

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

或者请使用这样的连接:

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

答案 1 :(得分:0)

我在你的问题中发现了两件错误的事情。

首先,您的查询:

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          |
+------+------------+------------+

请参阅屏幕截图:

CONCAT_WS Query