我正在使用以下代码进行计数,并对数据库中的值求和。
$query = "SELECT
COUNT(n.*) AS cnt_news,
COUNT(a.*) AS cnt_adv,
COUNT(c.*) AS cnt_comm,
SUM(CASE WHEN c.approve = '1' AND c.spam = '0' THEN 1 ELSE 0 END) AS cnt_approved,
SUM(CASE WHEN c.approve = '0' AND c.spam = '0' THEN 1 ELSE 0 END) AS cnt_unapproved,
SUM(CASE WHEN c.spam = '0' THEN 1 ELSE 0 END) AS cnt_spam,
SUM(a.amount) AS t_amnt,
SUM(a.cashpaid) AS t_cpaid,
SUM(a.balance) AS t_bal
FROM
news n, advertisements a, comments c";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
以下代码给出了错误,错误是
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) AS cnt_news, COUNT(a.*) AS cnt_adv, COUNT(c.*) AS cnt_c' at line 2
如果我删除了选择查询的前三行,它不显示错误,而是打印错误的值。
我的代码错了。 ??
以下代码对我来说非常合适。
$query = "SELECT COUNT(*) as cnt_news FROM news";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$query = "SELECT COUNT(*) as cnt_adv FROM advertisements";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$query = "SELECT COUNT(*) as cnt_comm FROM comments";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$query = "SELECT SUM(CASE WHEN c.approve = '1' AND c.spam = '0' THEN 1 ELSE 0 END) AS cnt_approved,
SUM(CASE WHEN c.approve = '0' AND c.spam = '0' THEN 1 ELSE 0 END) AS cnt_unapproved,
SUM(CASE WHEN c.spam = '1' THEN 1 ELSE 0 END) AS cnt_spam
FROM COMMENTS c";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$query = "SELECT SUM(a.amount) as t_amnt,
SUM(a.cashpaid) as t_cpaid,
SUM(a.balance) as t_bal
FROM advertisements a";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
我哪里错了?
答案 0 :(得分:1)
我放弃了将查询放入单个查询的想法,并且正如Col.Shrapnel所建议的那样,我为它做了一个自定义函数,我发现以这种方式维护代码非常容易。谢谢Col.Sharpnel我发布了他建议的答案。
这是我创建的用户定义函数。
function dbgetvar($query) {
$res = mysql_query($query);
if( !$res) {
trigger_error("dbget: ". mysql_error(). " in " .$query);
return false;
}
$row = mysql_fetch_array($res);
if(!$row) return "";
return $row;
}
然后我使用此代码调用了我的函数。
$news = dbgetvar("SELECT COUNT(*) as count FROM news");
$comments = dbgetvar("SELECT SUM(CASE WHEN c.approve = '1' AND c.spam = '0' THEN 1 ELSE 0 END) AS approved,
SUM(CASE WHEN c.approve = '0' AND c.spam = '0' THEN 1 ELSE 0 END) AS pending,
SUM(CASE WHEN c.spam = '1' THEN 1 ELSE 0 END) AS spam,
COUNT(*) AS count
FROM COMMENTS c");
$advertise = dbgetvar("SELECT SUM(a.amount) AS amount,
SUM(a.cashpaid) AS cashpaid,
SUM(a.balance) AS balance,
COUNT(*) AS count
FROM advertisements a");
上面的代码对我来说非常好。
答案 1 :(得分:0)
看起来Mysql不喜欢那条线。将COUNT(n.*)
更改为COUNT(n.id)
或该表的主键字段的名称。对a
和c
执行相同操作。
答案 2 :(得分:0)
您无法使用count(tablename.*)
,请尝试使用count(tablename.columnname)
答案 3 :(得分:0)
你可以尝试
SELECT(SELECT COUNT()FROM news)AS cnt_news, (SELECT COUNT()FROM FROM advertisements)为cnt_adv, ...