mysql的结果是逗号分隔的where子句

kqqjbcuj  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(366)

这种方法不需要我的where条件,但只要我搜索一种特定的口味,我就只能得到那种口味,但我想得到属于某个产品的所有口味。
我有两张table(简体):
产品

  1. | id | title |
  2. | 1 | exampleProduct |

口味

  1. | taste_id | product_id | taste_name |
  2. | 1 | 1 | cherry |
  3. | 2 | 1 | orange |

我希望我的结果是:

  1. | title | tastes |
  2. | exampleProduct | cherry, orange |

我已经尝试过此sql命令,但似乎不起作用:

  1. SELECT products.title, GROUP_CONCAT(tastes.taste_name) as tastes
  2. FROM products
  3. JOIN tastes on products.id = tastes.product_id
  4. WHERE tastes.taste_name = "cherry"
  5. GROUP BY products.id
368yc8dk

368yc8dk1#

我猜你想要所有的口味,而“樱桃”是其中之一。
如果是这样,则需要在聚合后进行比较:

  1. SELECT p.title, GROUP_CONCAT(t.taste_name) as tastes
  2. FROM products p JOIN
  3. tastes t
  4. ON p.id = t.product_id
  5. GROUP BY p.id
  6. HAVING SUM(t.taste_name = 'cherry') > 0;

相关问题