简体   繁体   English

关键字搜索,多个表,PHP和Mysql,要使用哪个Join?

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

I have 3 tables event, location, event_location. 我有3个表event,location,event_location。 Event can have multiple locations. 事件可以有多个位置。 Location table has lattitude, longitude, hasGeocode fields. 位置表具有经度,纬度和hasGeocode字段。

so for keywords "hello world" 因此,对于关键字“ hello world”

a simple query to Event table becomes 对事件表的简单查询成为

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

but if if the user has entered their location then I want to include location table in this query as well, so that users can specify their choice of location, how do i do this? 但是,如果用户输入了他们的位置,那么我也想在此查询中包括位置表,以便用户可以指定其位置选择,我该怎么做?

so essentially 3 types of search queries 因此本质上是3种搜索查询

  • just keywords 只是关键字

  • keywords and location 关键字和位置

  • keywords, proximity and a location 关键字,邻近度和位置

I tried something like this - 我尝试过这样的事情-

   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 mean event has to have one or more locations. 内部联接意味着事件必须具有一个或多个位置。 If an event hasnt got any location it wont appear in search results. 如果事件没有任何位置,它将不会出现在搜索结果中。 So please help me, how do I do this? 所以请帮助我,我该怎么做?

Thanks for you help. 感谢您的帮助。

You've got your join syntax all mangled up. 您的连接语法全部搞砸了。 In any case, if inner joins are not cutting it, use outer joins. 无论如何,如果内部连接没有切割,请使用外部连接。 ;-) ;-)

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

Also, the use of table aliases is never a bad idea, especially if your table names are long. 此外,使用表别名绝不是一个坏主意,尤其是在您的表名很长的情况下。

Use LEFT JOIN s (I altered the order of your joins and fixed the where clause location, which was misplaced) 使用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%' 

This way you'll get NULLs for events without location. 这样,对于没有位置的事件,您将获得NULL。

Also, try not to use select * but name the columns you are interested in. 另外,请尽量不要使用select *,而是将您感兴趣的列命名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM