2012-02-21 51 views
2

我有兩個表,作爲一個例子:搜索在不同的表,在不同的列名在MySQL

content 
- id 
- title 

news 
- id 
- myTitle 

所以我當時希望能夠同時搜索content.title和news.myTitle相同的關鍵字,但是我無法使用連接,因爲兩個表之間沒有外鍵。我試了幾個不同的查詢,但沒有返回我期待的結果,所以任何幫助將不勝感激。我只想要一個簡單的LIKE查詢來在兩個表中搜索title/myTitle。

+0

你是什麼意思與_the相同的keyword_? – DonCallisto 2012-02-21 10:07:33

回答

5
select content.title, 'content' as src_table from content where title = 'keyword' 
union 
select news.myTitle, 'news' as src_table from news where myTitle = 'keyword' 
+0

您已添加別名而不更新選擇條件。在這種情況下,別名確實不需要,因爲它們是簡單的選擇 – 2012-02-21 10:22:55

+0

我刪除它們以簡化查詢。 – 2012-02-21 10:25:35

+0

謝謝,這個作品很棒!有沒有辦法通過結果來判斷哪一行查詢來自哪個查詢?我只問,因爲我有一個不同的參數可以在我爲每個參數返回的URL中設置,而且不會每次都重新查詢以找出它來自哪個表。 – Ashley 2012-02-21 10:34:50

4

UNION是你在這件事情的朋友(背景閱讀:http://dev.mysql.com/doc/refman/5.6/en/union.html

(
    SELECT 
     'content', 
     id, 
     title 
    FROM content 
    WHERE title LIKE '%.....%' 
) 
UNION 
(
    SELECT 
     'news', 
     id, 
     myTitle AS title 
    FROM news 
    WHERE myTitle LIKE '%.....%' 
) 
1

怎麼樣?

select id, title from content 
where title like '%blah%' 
union all 
select id, myTitle from news 
where title like '%blah%' 

注意,如果你不使用union all,那麼你可能會失去一個記錄在那裏。目前尚不清楚你是否需要它。

相關問題