mysql查询失败原因不明(对我而言)

时间:2012-07-02 19:17:08

标签: php mysql

错误只显示查询的一部分,有人可以看到我犯的错误吗?

我想要的是根据标签获取条目,有3个表,nv_entries,nv_tags和nv_images。如果标签位于nv_tags表中,则应使用该表中的entrie_id从nv_entries和nv_images获取内容。

表格如下:

nv_entries:
id - title - year - etc..

nv_tags:
id - entrieid - tag

nv_images:
id - entrieid - source

查询失败:您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'GROUP BY nv_entries JOIN ON nv_entries.id = nv_tags.entrie_id AND nv_tags.tag IN'第1行附近使用正确的语法

在下面的脚本中生成的查询是这样的:

GROUP BY nv_entries JOIN ON nv_entries.id = nv_tags.entrie_id AND nv_tags.tag IN ('tree','green') HAVING COUNT(DISTINCT nv_tags.tag) = 2

这是脚本(部分):

for ($i = 0; $i < count($tags); $i++) {
    $tags[$i] = trim($tags[$i]);
}

$query = "GROUP BY nv_entries JOIN ON nv_entries.id = nv_tags.entrie_id AND nv_tags.tag IN (";
// add with following comma
for ($i = 0; $i < count($tags)-1; $i++) {
    $query .= "'".$tags[$i]."',";
}
// add last without a comma
$query .= "'".$tags[count($tags)-1]."'";

$query .= ") HAVING COUNT(DISTINCT nv_tags.tag) = ".count($tags);

echo $query;

$entries = execSelect($query);


echo "<pre>";
print_r($entries);
echo "</pre>";

1 个答案:

答案 0 :(得分:2)

您的查询格式错误!

感冒草案如下:

$sql ="
select e.*
from nv_entries e
JOIN nv_tags t on t.entrie_id = e.id
where t.tag in ( $tag_list )
group  by e.id
having count(t.id) = $num_tags ";

添加图片加入

此查询将为每个图像返回1行,使用 LEFT ,如果缺少图像,请避免丢失行。

$sql ="
select e.*, i.*, group_concat( t.tag separator ',') as tag_list
from nv_entries e
JOIN nv_tags t on t.entrie_id = e.id
LEFT JOIN nv_images i on i.entrie_id = e.id

where t.tag in ( $tag_list )
group  by e.id
having count(t.id) = $num_tags ";