2014-04-02 96 views
-1

我有三個表:如何從MySQL中的三個表中獲取數據?

  1. gallery_items
  2. gallery_album_items
  3. gallery_tags

我已經成功地加入了前兩個表,但我怎麼了gallery_tags表添加到下面的查詢?:

SELECT * 
FROM gallery_items 
RIGHT JOIN gallery_album_items 
ON gallery_items.id=gallery_album_items.id 
WHERE gallery_items.name LIKE '%{$term}%' 
OR gallery_items.description LIKE '%{$term}%' 

本質上是我想補充的:

OR gallery_tags.tag LIKE '%{$term}%' 

表結構

gallery_items 
id name  description 
12 Sharon This is sharon's description 
26 Rhett This is rhett's description 
33 Lincoln This is lincoln's description 


gallery_album_items 
id album 
12 14 
26 12 
33 7 


gallery_tags 
id item  tag 
23 12  blonde 
43 26  tall 
3 33  glasses 

本質上,結果我要爲 「金髮女郎」 的搜索: 沙龍金髮,是專輯#14

(你不必出示迴音聲明這僅僅是一個例子向您展示的結果。)

編輯 - 最後的答案

SELECT DISTINCT gallery_items.id 
FROM gallery_items 
RIGHT OUTER JOIN gallery_album_items ON gallery_items.id = gallery_album_items.id 
LEFT JOIN gallery_tags ON gallery_items.id = gallery_tags.item 
WHERE gallery_items.active != '0' 
AND (gallery_items.name LIKE '%blonde%' 
OR gallery_items.description LIKE '%blonde%' 
OR gallery_tags.tag LIKE '%blonde%' 
+0

僅供參考,請注意,RIGHT JOINs的出現時間大約是LEFT JOINs的1/20倍 - 只是說 – Strawberry

回答

2
SELECT * 

FROM gallery_items 

RIGHT OUTER JOIN gallery_album_items 

ON gallery_items.id=gallery_album_items.id 

LEFT OUTER JOIN gallery_tags 

ON gallery_tags.id = gallery_album_items.id  

WHERE gallery_items.name LIKE '%{$term}%' 

OR gallery_items.description LIKE '%{$term}%' 

OR gallery_tags.tag LIKE '%{$term}%' 
1

這個

SELECT * 
FROM gallery_items 
RIGHT JOIN gallery_album_items 
    ON gallery_items.id=gallery_album_items.id 
LEFT JOIN gallery_tags 
    ON gallery_tags.id = gallery_items.id 
WHERE gallery_items.name LIKE '%{$term}%' 
OR gallery_items.description LIKE '%{$term}%' 
1
SELECT * 
FROM gallery_items 
RIGHT JOIN gallery_album_items 
ON gallery_items.id=gallery_album_items.id 
LEFT JOIN gallery_tags on gallery_items.id on gallery_tags.id 
WHERE gallery_items.name LIKE '%{$term}%' 
OR gallery_items.description LIKE '%{$term}%' 
0

除了使用表名以外,還可以使用別名來編寫連接查詢,以便在思考邏輯的同時更好地理解。 我試過下面的一個,希望對你有幫助。


創建表的G_i( ID INT, 名VARCHAR(20), descp爲nvarchar(最大) )

插入件插入的G_i值(12, 'ASF 12', '描述12' ) 插入的G_i值(26, 'ASF 26', '描述26') INSERT INTO的G_i值(33, 'ASF 33', '描述33') SELECT * FROM的G_i


創建表G_A( ID INT, 專輯VARCHAR(20) ) INSERT INTO G_A值(12, '專輯12') INSERT INTO G_A值(26, '專輯26') INSERT INTO G_A值(33 , '相冊33') SELECT * FROM G_A


創建表G_T( ID INT, 項INT, 標籤爲nvarchar(40) ) INSERT INTO G_T值(23,12,'標籤12') 插入到g_t值(436,'tag 26') 插入G_T值(3,33, '標籤33') SELECT * FROM G_T


SELECT *

FROM的G_i如我RIGHT JOIN G_A作爲ON i.id = a.id LEFT JOIN G_T爲T上t.item = i.id

WHERE i.name LIKE '%T%' 或i.descp LIKE '%T%'


1

請嘗試這個

select gi.name, gai.ablum, gt.tag 
    from 
    gallery_items as gi JOIN gallery_album_items as gai 
    on gt.id=gai.id 
    Join gallery_tags as gt 
    on gi.id=gt.items 
相關問題