简体   繁体   中英

Use result from one query as an input into another query on MySQL

I am trying to use a result from one query as input for another query but I am stumped. I thought about using JOIN but I think in this case the two queries need to me run separately. Essentially I have a list of articles in my database. As I loop through the list or articles that I obtained from my first query I want to search a second table to find out the number of votes that each article has.

This is the code:

<?php
  $sql=mysql_query("SELECT * FROM discussion_links WHERE link_side = 'Michigan'");
  while($row = mysql_fetch_array($sql)) {
?>

<div class="top-links-wrapper">
    <div>
       <div class="link-info">
           <a class="link-title" href="http://<?php echo $row['link_url'] ?>">
           <?php echo $row['link_title'] . "</a>"; ?>
           <p class="link-source"><?php echo $row['link_source'] . "</p>" ?>
       </div>
       <div class="link-vote-wrapper">
           <span class="link-votes">
           <?php    
                $sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id'] .")";
                $num_rows = mysql_num_rows($sql2);
                echo "$num_rows";
            ?>
           </span>
       </div>
    </div>
</div>

Thanks

You can join both queries try this

SELECT dl.* , lv.*
FROM discussion_links dl
LEFT JOIN link_votes lv ON lv.link_id = dl.link_id
WHERE link_side = 'Michigan'

Change

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id'] .")";

to

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id']);

The closing bracket ) is part of the function call not the query

or better would be to create a single query :

SELECT * FROM discussion_links d 
JOIN link_votes v
on d.link_id = v.link_id
WHERE d.link_side = 'Michigan'

You should replace the SELECT * and just select the columns you require

Fixed, had an error in the 2nd query:

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id']);

It now works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM