MYSQL连接和计数语法错误

时间:2015-02-12 12:18:19

标签: php mysql

Table:articles
id  address     autor   .........
1   name_test1  Paul    ...........
2   name_test2  George  ........

此表包含一些博文。

Table:article-hearts
id  cookie_userid   article_id
1   123             1
2   345             1
3   123             2

当访问者点击" Heart It!"行动记录在这里。

我想显示每篇博文的心数。 在这种语法中,我试图添加心脏计数:

$articles = mysql_query("SELECT * FROM articles ORDER BY date_created, time_created DESC ") or die(mysql_error());

所以它看起来像这样:

 $articles = mysql_query("SELECT a.id, a.address, a.autor, a.date_created, a.time_created, a.title, a.content, a.category, a.reads, ah.cookie_userid, ah.article_id, ah.id, 
COUNT(*) as 'hcount'
FROM
articles AS a
    join 'article_hearts' AS ah where 'ah.article_id' = 'a.id'
    join 'article_hearts' AS ah2 where ah2.article_id=ah.article_id
ORDER BY a.date_created, a.time_created DESC
")or die(mysql_error());

我在第5行得到错误:加入' article_hearts' AS啊在哪里' ah.article_id' =' a.id'

2 个答案:

答案 0 :(得分:1)

你的语法错了。在连接之后必须是on条件而不是`where considtion。您还必须删除列名称旁边的单引号。

SELECT a.id, a.address, a.autor, a.date_created, a.time_created, a.title, a.content, a.category, a.reads, ah.cookie_userid, ah.article_id, ah.id, 
COUNT(*) as 'hcount'
FROM
articles AS a
    join 'article_hearts' AS ah on ah.article_id= a.id
    join 'article_hearts' AS ah2 on ah2.article_id=ah.article_id
ORDER BY a.date_created, a.time_created DESC

答案 1 :(得分:0)

有5个问题:

  • 表格中的引言
  • 两次加入桌子
  • 加入的语法错误
  • 缺少GROUP BY
  • 您在选择

    中不需要某些列

    $articles = mysql_query( "SELECT a.id, a.address, a.autor, a.date_created, a.time_created, a.title, a.content, a.category, a.reads, COUNT(*) as 'hcount' FROM articles AS a JOIN article_hearts AS ah ON ah.article_id = a.id GROUP BY a.id, a.address, a.autor, a.date_created, a.time_created, a.title, a.content, a.category, a.reads ORDER BY a.date_created, a.time_created DESC") or die(mysql_error());