我在這個主題找到幫助:Search different column names in different tables in MySQL但他們只引用該主題中的每個表的兩個字段,我無法從我的搜索生成一個答案。搜索兩個不同的MySQL表與不同的字段
編輯:我還發現這個線程:Combine two tables that have no common fields這給多一點有用的信息,但我仍然無法弄清楚如何組合這些正確
我從未有過需要建立一個JOIN
或UNION
查詢,所以這對我來說都很新。所以請原諒我,如果有一個簡單的解決方案。
我需要運行一個查詢,該查詢將搜索具有完全不同字段的兩個不同數據庫表。
這裏有兩個查詢我試圖合併爲一個:
"SELECT * FROM seekers
WHERE (first_name LIKE '%".$q."%')
OR (last_name LIKE '%".$q."%')
OR (username LIKE '%".$q."%')
OR (school LIKE '%".$q."%')
OR (major LIKE '%".$q."%')
OR (employer LIKE '%".$q."%')
OR (position LIKE '%".$q."%')
OR (background LIKE '%".$q."%')
OR (interests LIKE '%".$q."%')
OR (skills LIKE '%".$q."%')
ORDER BY id DESC"
"SELECT * FROM companies
WHERE (company_name LIKE '%".$q."%')
OR (username LIKE '%".$q."%')
OR (industry LIKE '%".$q."%')
OR (slogan LIKE '%".$q."%')
OR (location LIKE '%".$q."%')
ORDER BY id"
查詢之後,我想所有的字段到一個數組中,並相應地顯示數據。
我想我遇到的主要問題是決定如何組合表格?我想使用JOIN
(內部還是外部),還是我想使用UNION
?
我試圖創建一個VIEW
這樣做:$this->mysqli->query("CREATE VIEW userTable AS (SELECT * FROM seekers) UNION ALL (SELECT * FROM companies)");
但這並沒有工作,我猜測,因爲表有很多不同的領域。
編輯:嘗試以下一些問題的答案後,我想出了這個查詢:
SELECT first_name, last_name, username, school, major, employer, position, background, interests, skills
FROM seekers
WHERE (first_name LIKE '%".$q."%')
OR (last_name LIKE '%".$q."%')
OR (username LIKE '%".$q."%')
OR (school LIKE '%".$q."%')
OR (major LIKE '%".$q."%')
OR (employer LIKE '%".$q."%')
OR (position LIKE '%".$q."%')
OR (background LIKE '%".$q."%')
OR (interests LIKE '%".$q."%')
OR (skills LIKE '%".$q."%')
UNION ALL
SELECT company_name, username, industry, slogan, location, NULL, NULL, NULL, NULL, NULL
WHERE (company_name LIKE '%".$q."%')
OR (username LIKE '%".$q."%')
OR (industry LIKE '%".$q."%')
OR (slogan LIKE '%".$q."%')
OR (location LIKE '%".$q."%')
我刪除了ORDER BY
子句,因爲我得到了一個錯誤說「不正確地使用UNION和秩序BY「,所以在刪除ORDER BY
後,我得到這樣的錯誤:」查詢失敗:你的SQL語法有錯誤;查看與你的MySQL服務器版本相對應的手冊,查找'WHERE(company_name LIKE'%' 0%')OR(用戶名LIKE'%0%')或(行業LIKE'%0%')'在線1「
爲什麼$q
在聯合後的查詢中變爲0?
編輯#2:這是一個JOIN
查詢我放在一起,實際上返回數據,但它不會返回正確的數據。我不知道這是否有助於回答這個問題,但我想我會把它放在這裏。
"SELECT * FROM seekers t1 LEFT JOIN companies t2 ON t1.id = t2.id WHERE (t1.first_name LIKE '%".$q."%') OR (t1.last_name LIKE '%".$q."%') OR (t1.username LIKE '%".$q."%') OR (t1.school LIKE '%".$q."%') OR (t1.major LIKE '%".$q."%') OR (t1.employer LIKE '%".$q."%') OR (t1.position LIKE '%".$q."%') OR (t1.background LIKE '%".$q."%') OR (t1.interests LIKE '%".$q."%') OR (t1.skills LIKE '%".$q."%') OR (t2.company_name LIKE '%".$q."%') OR (t2.username LIKE '%".$q."%') OR (t2.industry LIKE '%".$q."%') OR (t2.slogan LIKE '%".$q."%') OR (t2.location LIKE '%".$q."%')"
對於最後一個查詢的格式化感到抱歉,所以在粘貼時弄錯了它。
也許這將幫助:http://stackoverflow.com/questions/7407864/mysql-select-union- for-different-columns – 2013-03-01 23:13:46