douxian7117 2011-11-28 22:49
浏览 57
已采纳

使用来自一个MySQL查询的结果插入到另一个查询中

I am trying to use PHP and MySQL to automatically generate a list like this.

Subject #1

  • Resource #3
  • Resource #5
  • Resource #12

Subject #2

  • Resource #7
  • Resource #4
  • Resource #1

etc.

Here are the tables:

eresources

  • erid
  • etitle

subjects

  • sid
  • stitle

subjectmap

  • sid
  • erid

Here is the code that successfully gives me all the subjects in alphabetical order:

$subjectQuery = "SELECT * FROM subjects WHERE sid != 17 ORDER BY stitle ASC";
$subjectResult = $mysqli->query($subjectQuery);

while ($subjectArray = $subjectResult->fetch_assoc()) { 
print "<h5 class='subcategory'>" . $subjectArray['stitle'] . "</h5>";
print "<div class='inner'>  

// Need a list of resources that match each subject ID (sid) here!

</div>";
}

Now, here is the code that successfully gives me all the e-resources with a fixed subject ID:

$getERBySubjectQuery = " SELECT erid FROM subjectmap WHERE sid=11 ";
$getERBySubjectResult = $mysqli->query($getERBySubjectQuery);
if($getERBySubjectResult && $getERBySubjectResult->num_rows >= 1){
 while($getERBySubjectArray = $getERBySubjectResult->fetch_assoc() ){
        $query = " SELECT * FROM eresources WHERE erid = " .$getERBySubjectArray['erid']. " ORDER BY ertitle ASC ";
    $result = $mysqli->query($query);

    if($result && $result->num_rows >= 1){
       while($array = $result->fetch_assoc() ){
          print("<a href=\"" . $array['link'] . "\">" .   "<h5 class='subcategory'>" . $array['ertitle'] . "<div class='accessnote'>"   .  $array['access']    . "</div></h5></a>");

 }}}}

Naturally, I am not inclined to duplicate the same stanza for each subject ID (sid). I want the list of subjects to be generated automatically and the list of resources that have that subject to be generated automatically as well.

Basically I need to feed the sid from the first stanza into the second stanza for each subject.

  • 写回答

2条回答 默认 最新

  • dragon0023 2011-11-29 00:06
    关注

    By using a WHERE clause instead, I think Frits van Campen's query could be more human readable, especially for a beginner :

    SELECT subject.stitle, eresource.etitle
    FROM subject,subjectmap,eresource 
    WHERE subject.id = subjectmap.sid
      AND eresource.id = subjectmap.erid
    ORDER BY subject.stitle, eresource.etitle
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试