2009-07-07 41 views
1

我有3個表事件,位置,event_location。活動可以有多個地點。 位置表具有經度,緯度和Geocode字段。關鍵字搜索,多表,PHP和Mysql,哪些Join可以使用?

所以對於關鍵字的「Hello World」

簡單查詢事件表變得

Select * from event where keywords like '%hello%' OR keywords like '%world%' 

,但如果如果用戶已經進入了他們的位置,然後我想在此查詢位置表,以及,以便用戶可以指定他們的位置選擇,我該如何做?

所以基本上是3種類型的搜索查詢

  • 不僅僅是關鍵字

  • 關鍵字和地址

  • 關鍵字,接近和位置

我想是這樣的 -

select * from event where keywords like '%hello%' OR 
    keywords like '%world%' INNER JOIN location ON 
    location.location_id = event_location.location_id 
    INNER JOIN 
    event_location ON event_location.event_id = event.event_id 

INNER JOINs意味着事件必須有一個或多個位置。如果一個事件沒有得到任何位置,它不會出現在搜索結果中。所以請幫助我,我該怎麼做?

感謝您的幫助。

回答

2

你有你的加入語法都錯位了。無論如何,如果內部連接不切割它,請使用外部連接。 ;-)

SELECT 
    * 
FROM 
    event AS e 
    LEFT JOIN event_location AS el ON el.event_id = e.event_id 
    LEFT JOIN location  AS l ON l.location_id = el.location_id 
WHERE 
    e.keywords LIKE '%hello%' 
    OR e.keywords LIKE '%world%' 

此外,使用表別名從來都不是一個壞主意,特別是如果您的表名很長。

+0

這解決了我的問題 – Fil 2016-04-15 09:38:14

1

使用LEFT JOIN S(我改變了你的加入順序和固定的where子句的位置,這是沒有道理的)

select * from event LEFT JOIN event_location ON 
event.event_id = event_location.event_id 
LEFT JOIN 
location ON event_location.location_id = location.location_id 
where keywords like '%hello%' OR 
keywords like '%world%' 

這樣你會得到事件的NULL沒有位置。

此外,儘量不要使用select *,但名字你感興趣的列。