此查询工作正常:
SELECT posts.titulo as value,
posts.id as id,
posts.img_src as img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id as fm,
textos.clave,
textos.texto as familia,
FROM posts,familias,textos
WHERE posts.id_familia = familias.id AND familias.clave = textos.clave AND textos.lengua = ".detectarIdioma()."
and posts.id_usuario = $term
ORDER BY posts.id DESC
但是现在我想添加一篇帖子有多少评论,这是在comentarios表中
SELECT posts.titulo as value,
posts.id as id,
posts.img_src as img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id as fm,
textos.clave,
textos.texto as familia,
count(comentarios.id)
FROM posts,familias,textos
JOIN comentarios ON comentarios.id_post = posts.id
WHERE posts.id_familia = familias.id AND familias.clave = textos.clave AND textos.lengua = ".detectarIdioma()."
and posts.id_usuario = $term
ORDER BY posts.id DESC
问题是mysql错误是
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 '*)
FROM posts,familias,textos
JOIN comentarios ON ' at line 12
知道我在这里缺少什么吗?
答案 0 :(得分:1)
尝试这样的事情:
SELECT posts.titulo AS value,
posts.id AS id,
posts.img_src AS img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id AS fm,
textos.clave,
textos.texto AS familia,
COALESCE(COM_COUNT.NUM_COMMENTS,0) AS num_comments
FROM posts
INNER JOIN familias ON posts.id_familia = familias.id
INNER JOIN textos familias.clave = textos.clave
LEFT JOIN
( SELECT id_post, COUNT(*) AS NUM_COMMENTS
FROM comentarios
GROUP BY id_post
) COM_COUNT ON COM_COUNT.id_post = posts.id
WHERE AND textos.lengua = ".detectarIdioma()."
AND posts.id_usuario = $TERM
ORDER BY posts.id DESC
这将使每个帖子的评论数量加入,如果JOIN不匹配则显示为0.
答案 1 :(得分:0)
试试这个:
SELECT posts.titulo as value,
posts.id as id,
posts.img_src as img,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id as fm,
textos.clave,
textos.texto as familia,
count(comentarios.id)
FROM posts INNER JOIN familias ON posts.id_familia = familias.id
INNER JOIN textos ON familias.clave = textos.clave
LEFT OUTER JOIN comentarios ON comentarios.id_post = posts.id
WHERE textos.lengua = ".detectarIdioma()."
AND posts.id_usuario = $term
GROUP BY posts.titulo,
posts.id,
posts.img_src,
posts.id_familia,
posts.tiempo,
posts.votos,
familias.clave,
familias.id,
textos.clave,
textos.texto
ORDER BY posts.id DESC
您只是混合了两种JOIN
语法。
......除了你正在计算的那一列之外,你可能需要按每列进行分组。
编辑:要不将结果限制为仅包含评论的人,您需要在该表上执行LEFT OUTER JOIN
。
答案 2 :(得分:0)
您在第一个查询中的FROM之前有一个逗号,但在第二个查询中没有FROM之前的逗号