簡體   English   中英

關鍵字搜索,多個表,PHP和Mysql,要使用哪個Join?

[英]Keyword search, multiple tables, PHP and Mysql, Which Join to use?

我有3個表event,location,event_location。 事件可以有多個位置。 位置表具有經度,緯度和hasGeocode字段。

因此,對於關鍵字“ 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

內部聯接意味着事件必須具有一個或多個位置。 如果事件沒有任何位置,它將不會出現在搜索結果中。 所以請幫助我,我該怎么做?

感謝您的幫助。

您的連接語法全部搞砸了。 無論如何,如果內部連接沒有切割,請使用外部連接。 ;-)

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%' 

此外,使用表別名絕不是一個壞主意,尤其是在您的表名很長的情況下。

使用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 *,而是將您感興趣的列命名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM