我如何使用PHP返回加入查询的结果?

时间:2011-06-06 07:59:35

标签: php subquery

查询如下:

  SELECT v2.video_id
    FROM `VideoTags` AS v1
    JOIN `VideoTags` AS v2 USING ( tag_id )
   WHERE v1.video_id =1
     AND v1.video_id <> v2.video_id
GROUP BY v2.video_id
ORDER BY COUNT( * ) DESC

我正在尝试获取相关视频,当我在phpmyadmin中运行此查询时,它返回正确的结果集但是当我尝试使用php编写此内容并回显结果时,我得不到返回的值,我使用的查询代码是:

$result = mysql_query("SELECT v2.video_id FROM `VideoTags` AS v1 JOIN `VideoTags` AS v2 USING ( tag_id ) WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC"); 

$row = mysql_fetch_array( $result );

echo "ID ".$row['video_id'];

我确定它简单的东西我似乎无法弄明白?如果有人可以帮忙...

3 个答案:

答案 0 :(得分:0)

尝试使用此查询: SELECT v2.video_id as v2id FROM VideoTags AS v1 JOIN VideoTags AS v2 USING ( tag_id ) WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC

然后

echo "ID ".$row['v2id'];

答案 1 :(得分:0)

它返回一个数组,以便你可以将它循环出去

$result = mysql_query("SELECT v2.video_id FROM `VideoTags` AS v1 JOIN `VideoTags` AS v2 USING ( tag_id ) WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC"); 

while ($row = mysql_fetch_array( $result )) {
    echo "ID " . $row[0] . "<br />";
}

答案 2 :(得分:0)

我不确定为什么它不会让我对Trikks的答案发表评论,但他基本上是正确的,除了一件事,所以我会把它给他。而不是$ row [0],你会想要$ row ['video_id']; (根据提供的例子)。我将回声更改为单引号,因为你没有在回声中使用变量,单引号比双引号更快。

$result = mysql_query("SELECT v2.video_id FROM `VideoTags` AS v1 JOIN `VideoTags` AS v2 USING ( tag_id ) WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC"); 

while ($row = mysql_fetch_array( $result ))
{
    echo 'ID ' . $row['video_id'] . '<br />';
}

编辑:此外,如果您没有收到任何值,我会检查您是否使用print_r(array_key($row));使用了正确的密钥:

$result = mysql_query("SELECT v2.video_id FROM `VideoTags` AS v1 JOIN `VideoTags` AS v2 USING ( tag_id ) WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC"); 

while ($row = mysql_fetch_array( $result ))
{
    print_r(array_key($row));
    echo 'ID ' . $row['video_id'] . '<br />';
}