Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.video_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.

like image 654
James Rand Avatar asked Oct 26 '25 03:10

James Rand


2 Answers

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
)
like image 99
mkilmanas Avatar answered Oct 28 '25 18:10

mkilmanas


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.

like image 32
Jagadeesan Avatar answered Oct 28 '25 18:10

Jagadeesan