duanlv2788 2013-08-07 17:28
浏览 65
已采纳

在彼此内部使用多个mysql查询循环

i have a big trouble using multiple queries inside each other. and i searched for it but could not find what i needed! so this is my problem. plz help me.

i have a table named "cat" and i get the titles by mysql and it's ok. i have an other table named works that has a field named "Cat_ID" this is the field that connect's the data of both tables. works table has another field named "Years" and it's the year of the production of artwork.

cat >> { ID , Title , ... } works >> { ID , Title , URL , Year , Cat_ID , ... }

i need to categorize the gallery of works by year, so i made a code like this:

<?php
$result = q("cat");
while($row = mysqli_fetch_array($result)) { ?>
  <div>
    <h2><a href="artwork.php?id=<?php echo $row['ID'] ?>"> <?php echo $row['Title']; ?></a></h2>
    <span>
    <?php
      $sql = "SELECT DISTINCT Year FROM works WHERE Cat=".$row['Cat_ID'];
      $yresult = mysql_query($sql);
      while ($yrow = mysql_fetch_row($yresult)) 
      {
        //and print it as anchor here but it wont get into loop at all!                         
      }                         
    ?>
    </span>
  </div>
<?php } ?>

the q() is a function that just connects to DB and run the query. this line works pretty well. but the it wont enter to the inner while at all! i checked and saw that the $yrow is totally empty(by EMPTY() of php)! what can i do about it? it seems that mysql can not execute the second query at all! the solution must be in two ways i think. 1. make mysql to execute the second query. 2. change the first query in the way that get's the years distinctly and read them by mysql_fetch_array and put the years as anchor via for each.

plz help me.

  • 写回答

1条回答 默认 最新

  • dongqiuxu2270 2013-08-07 17:34
    关注

    Instead of having multiple loops, use an INNER JOIN:

    SELECT DISTINCT works.Year FROM cat INNER JOIN works ON (cat.ID = works.Cat_ID)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 找人不需要人工智能回答的gamit解算后做形变分析
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错