【问题标题】:Having trouble with mysql countmysql计数有问题
【发布时间】:2015-06-16 20:37:09
【问题描述】:

执行查询后出现此错误

1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法使用 near '*) as totalcontents from contents as c 内连接类别 as cat ON cat.id = ' 在第 1 行

我的sql是这样的

select z.name as zone_name, COUNT(c.*) as totalcontents 
from contents as c 
inner join categories as cat 
ON cat.id = c.category_id 
inner join zones as z 
ON z.id = cat.zone_id where c.created_by = 14 group by z.id

【问题讨论】:

  • 试试COUNT(c.id) as totalcontents

标签: php mysql


【解决方案1】:

当您使用INNER JOIN 时,COUNT(*) 可以使用。

select z.name as zone_name, COUNT(*) as totalcontents  ....

select z.name as zone_name, COUNT(z.name) as totalcontents  ....

Go through this

【讨论】:

  • 你是通过z.id指定组并用z.name选择,它没有给出错误
  • 列 'z.name' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
  • 我的回答只解决了它遇到的错误。 COUNT(*) 也解决了这个问题。在我的示例中,我认为我没有使用任何 GROUP BY
【解决方案2】:

当您使用 group by 函数指定列显示列时,其他列显示给定错误。我想你试试这个

select z.name as zone_name, COUNT(z.name) as totalcontents 
from contents as c 
inner join categories as cat 
ON cat.id = c.category_id 
inner join zones as z 
ON z.id = cat.zone_id where c.created_by = 14 group by z.name

select z.name as zone_name,totalcontents 
from zones as z
join (select z.id as id, COUNT(z.id) as totalcontents 
    from contents as c 
    inner join categories as cat 
    ON cat.id = c.category_id 
    inner join zones as z 
    ON z.id = cat.zone_id where c.created_by = 14 group by z.id) a
ON z.id = a.id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多