【问题标题】:MYSQL - Group by two columns doesn't workMYSQL - 按两列分组不起作用
【发布时间】:2022-11-21 20:45:17
【问题描述】:

我有 2 个表、产品和该产品的标签 - 我尝试获取具有最多联合标签和用户标签的产品。

所以我的代码看起来像:

SELECT 
    count(tags.id) AS best, 
    products.* 
from tags 
LEFT JOIN products ON products.idprod=tags.idprod 
where 
    ( tags.short = "one" OR tags.short = "two" OR tags.short = "four")
GROUP BY products.idprod, products.category
HAVING best > 2 
ORDER BY best DESC 
limit 8

问题是,在我的结果中,产品是按产品 ID (idprod) 分组的,而不是按类别分组的(应该只有一个类别的一个产品)。

有任何想法吗?

【问题讨论】:

  • 你得到什么错误?我们不知道表 products 有多少列和哪些列......

标签: mysql group-by


【解决方案1】:

组中的列需要出现在选择中

尝试这个:

SELECT 
    products.idprod, products.category,count(tags.id) AS best
from tags 
LEFT JOIN products ON products.idprod=tags.idprod 
where 
    ( tags.short = "one" OR tags.short = "two" OR tags.short = "four")
GROUP BY products.idprod, products.category
HAVING best > 2 
ORDER BY best DESC 
limit 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多