作爲個人項目,我只是爲了好玩,爲了學習的目的而創建了一個PHP和MySQL字典。然而,當我試圖更精確地瞭解MySQL如何檢索字典條目時,我遇到了一個問題。使用MySQL執行復雜的多表搜索查詢
我的查詢的目的是在'entries'表中搜索提供的單詞作爲'單詞'(詳見下文),如果找到結果,則列出'alternatives'中的每個'alternative'用它。
但是,如果沒有找到結果,則查詢將搜索'alternatives',搜索提供的單詞作爲'alternative',然後從'entries'表中返回相同的結果並使用相同的單詞」。
我能夠用這個草率的代碼來實現這一點:
SELECT alternatives.word, alternatives.alternative, entries.added
FROM alternatives
INNER JOIN entries
ON entries.word = alternatives.word
WHERE entries.word = (SELECT word
FROM alternatives
WHERE alternative = "randomword"
OR word = "randomword" LIMIT 1)
不幸的是,這個代碼不考慮這個的一個關鍵問題,這就是一個字可以在「替代」,但仍有條目。 (例如,「條目」可能包含「查詢」和「查詢」,而「查詢」將查看「查詢」作爲替代方案,而「查詢」將查看「查詢」作爲替代方案。)
'替代表:
id | word [the word the alternative word is based on] | alternative [alternative word] | type [verb/noun/adjective etc...]
的 '項' 表:
id | word [the word] | date [timestamp of entry, must be returned]
有沒有簡單的解決這個問題?我現在完全卡住了。
我試圖運行這個,但它給了我一個錯誤:'#1064 - 你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'IF EXISTS(SELECT * FROM entries WHERE word =「wordtosearch」)BEGIN SELECT''第1行'附近使用正確的語法' – Forest
對不起,我習慣於使用SQL服務器和MYSQL語法稍有不同。我編輯了我的答案。 –