2011-11-28 185 views
0

我試圖使用PHP和MySQL來自動生成一個像這樣的列表。使用從一個MySQL查詢插入到另一個查詢

對象#1

  • 資源#3
  • 資源#5
  • 資源#12

受試者#2

  • 資源#7
  • Resourc È#4
  • 資源#1

下面是表:

eresources

  • ERID
  • etitle

個科目

  • SID
  • stitle

subjectmap

  • SID
  • ERID

下面是成功給了我所有的subje代碼按字母順序CTS:

$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>"; 
} 

現在,這裏是唯一成功給了我所有的電子資源具有固定主題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>"); 

}}}} 

當然,我不傾向於複製相同節每個主題ID(sid)。我希望自動生成主題列表以及自動生成主題的資源列表。

基本上我需要從第一節喂sid到每個主題的第二節。

+0

謝謝你們的Frits和Djangofan的回覆。非常感激! –

回答

1

通過使用WHERE子句相反,我認爲弗裏茨麪包車坎彭的查詢可以更人類可讀的,特別是對於初學者:

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

不執行n+1查詢,其中n爲主體的數量,您不能這樣做在MySQL。

您可以使用JOIN和一些巧妙的排序。

SELECT 
    subject.stitle, eresource.etitle 
FROM subject 
    LEFT JOIN subjectmap ON subject.id = subjectmap.sid 
    LEFT JOIN eresource ON eresource.id = subjectmap.erid 
ORDER BY subject.stitle, eresource.etitle 

你會得到這樣一個結果:

+------------+--------------+ 
| stitle  | etitle  | 
+------------+--------------+ 
| Subject #1 | Resource #3 | 
| Subject #1 | Resource #5 | 
| Subject #1 | Resource #12 | 
| Subject #2 | Resource #1 | 
| Subject #2 | Resource #4 | 
| Subject #2 | Resource #7 | 
+------------+--------------+