MySQL 结果以逗号分隔,用 WHERE 子句分隔
MySQL results as comma seperated with WHERE clause
这在没有我的 WHERE 条件的情况下有效,但是一旦我搜索特定口味,结果我只会得到那个口味,但我想收到属于产品的所有口味。
我有 2 个表(简化):
产品
| id | title |
| 1 | exampleProduct |
口味
| taste_id | product_id | taste_name |
| 1 | 1 | cherry |
| 2 | 1 | orange |
我希望我的结果是:
| title | tastes |
| exampleProduct | cherry, orange |
我已经尝试过这个 SQL 命令,但它似乎不起作用:
SELECT products.title, GROUP_CONCAT(tastes.taste_name) as tastes
FROM products
JOIN tastes on products.id = tastes.product_id
WHERE tastes.taste_name = "cherry"
GROUP BY products.id
我猜你想要各种口味,而 "cherry" 就是其中之一。
如果是这样,您需要在聚合之后进行比较:
SELECT p.title, GROUP_CONCAT(t.taste_name) as tastes
FROM products p JOIN
tastes t
ON p.id = t.product_id
GROUP BY p.id
HAVING SUM(t.taste_name = 'cherry') > 0;
这在没有我的 WHERE 条件的情况下有效,但是一旦我搜索特定口味,结果我只会得到那个口味,但我想收到属于产品的所有口味。
我有 2 个表(简化):
产品
| id | title |
| 1 | exampleProduct |
口味
| taste_id | product_id | taste_name |
| 1 | 1 | cherry |
| 2 | 1 | orange |
我希望我的结果是:
| title | tastes |
| exampleProduct | cherry, orange |
我已经尝试过这个 SQL 命令,但它似乎不起作用:
SELECT products.title, GROUP_CONCAT(tastes.taste_name) as tastes
FROM products
JOIN tastes on products.id = tastes.product_id
WHERE tastes.taste_name = "cherry"
GROUP BY products.id
我猜你想要各种口味,而 "cherry" 就是其中之一。
如果是这样,您需要在聚合之后进行比较:
SELECT p.title, GROUP_CONCAT(t.taste_name) as tastes
FROM products p JOIN
tastes t
ON p.id = t.product_id
GROUP BY p.id
HAVING SUM(t.taste_name = 'cherry') > 0;