我正在尝试使用PHP和MySQL自动生成这样的列表。
主题#1
主题#2
等
以下是表格:
eresources
受试者
subjectmap
以下是按字母顺序成功提供所有主题的代码:
$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 :(得分: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 |
+------------+--------------+
答案 1 :(得分:1)
通过使用WHERE子句,我认为Frits van Campen的查询可能更具人性化,特别是对于初学者:
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