Write a query to get an array and use that array in a subquery
What I am trying to do is get the results from the first query pass them into an array and then use them in a sub query. Both queries work separately if I input the id's into the sub query manually. Is there a way of linking these two queries?
I have used this code
$result = mysql_query("SELECT v2.video_id as v2id FROM VideoTags AS v1 JOIN VideoTags AS v2 USING ( tag_id ) WHERE v1.vid开发者_开发百科eo_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC");
$values = array();
while ($row = mysql_fetch_array( $result )) {
$values[] = $row['v2id'];
}
echo join(", ", $values);
$resultone = mysql_query("SELECT * FROM videos WHERE video_id IN (' . join(',', $values). ')");
while ($row = mysql_fetch_array( $resultone )) {
echo "name ".$row['video_name'];
}
Thanks for your help.
Yes, it's called subquery (and what you use is not subquery, because it does not contain one query inside another.
SELECT *
FROM videos
WHERE video_id IN (
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
)
This is enough
$resultone = mysql_query("SELECT * FROM videos WHERE video_id IN (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)");
while ($row = mysql_fetch_array( $resultone )) {
echo "name ".$row['video_name'];
}
But before using query like this, check your mysql version for subquery support.
You could do this in one query.
$innersql = "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");
$sql= mysql_query("SELECT * FROM videos WHERE video_id IN (" . $innersql .")");
while ($row = mysql_fetch_array( $resultone )) {
echo "name ".$row['video_name'];
}
Hope this helps.
SELECT * FROM VideoTags AS v1 JOIN VideoTags AS v2 USING ( tag_id )
inner join video vi on vi.video_id = v1.video_id
WHERE v1.video_id =1 AND v1.video_id <> v2.video_id GROUP BY v2.video_id ORDER BY COUNT( * ) DESC");
The count(*) does not make sence ?
精彩评论