我正在構建一個搜索頁面,表單將變量傳遞給SQL查詢。如果我輸入任何搜索參數,我會得到我想要的結果,除非我將作者或主題搜索留空,如果有多個作者和/或與結果相關的主題,我會得到多個結果。我的大部分記錄都有多個作者或多個主題。顯示多個結果的MySQL查詢
基本問題是,如果有一個記錄有2個作者和3個相關主題,那麼我會得到6個結果。
我試圖達到的目標:我試圖修改查詢,以便只接收一條記錄(record_ID是唯一的),即使有多個作者或多個主題。
查詢中的2個連接有問題是拉作者和主題。例如,對於得到的作者,我用這個連接(主題JOIN幾乎是相同的)和變量$ fauthor從PHP傳入:
SELECT la.author, la.author_ID, ra.record_ID
FROM lib_author AS la
JOIN record_author AS ra ON la.author_ID = ra.author_ID
JOIN lib_record AS lr ON ra.record_ID = lr.record_ID
WHERE la.author LIKE '%$fauthor%'
相關的表是lib_author [AUTHOR_ID,作者] lib_record [RECORD_ID,...],並record_author [RECORD_ID,AUTHOR_ID]
下面是完整的查詢:
select a.record_ID, a.year, n.title, y.author, y.author_ID, j.journal, pox.publisher, lox.language, a.volume, a.issue, a.pages, a.abstract, s.subject
FROM lib_record AS a
JOIN lib_title as n on n.title_ID = a.title_ID
JOIN (SELECT la.author, la.author_ID, ra.record_ID
FROM lib_author AS la
JOIN record_author AS ra ON la.author_ID = ra.author_ID
JOIN lib_record AS lr ON ra.record_ID = lr.record_ID
WHERE la.author LIKE '%$fauthor%') AS y
JOIN (SELECT ls.subject, ls.subject_ID, rs.record_ID
FROM lib_subject AS ls
JOIN record_subject AS rs ON ls.subject_ID = rs.subject_ID
JOIN lib_record AS lr ON rs.record_ID = lr.record_ID
WHERE ls.subject LIKE '%$fsubject%') AS s
JOIN lib_journal AS j on j.journal_ID = a.journal_ID
JOIN lib_publisher pox ON a.publisher_ID = pox.publisher_ID
JOIN lib_language lox ON a.language_ID = lox.language_ID
WHERE y.record_ID = a.record_ID
AND s.record_ID = a.record_ID
AND n.title LIKE '%$ftitle%'
AND j.journal LIKE '%$fjournal%'
我希望有人有一些見解。謝謝
如果您有多個作者,列出,預期的結果是什麼?只需選擇第一個,或者抓住逗號分隔的列表? –
預期結果是顯示與記錄相關的數據的單行。該行是一個href,將用戶發送到卡片目錄並顯示所有信息。 –