【问题标题】:Keyword search, multiple tables, PHP and Mysql, Which Join to use?关键字搜索,多表,PHP和Mysql,使用哪个Join?
【发布时间】:2010-11-08 17:07:21
【问题描述】:

我有 3 个表事件、位置、事件位置。事件可以有多个位置。 位置表有纬度、经度、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

INNER JOIN 意味着事件必须有一个或多个位置。如果一个事件没有得到任何位置,它就不会出现在搜索结果中。所以请帮助我,我该怎么做?

感谢您的帮助。

【问题讨论】:

    标签: php mysql search join


    【解决方案1】:

    你的连接语法已经被弄乱了。在任何情况下,如果内部连接没有切割它,请使用外部连接。 ;-)

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

    此外,使用表别名也不是一个坏主意,尤其是在您的表名很长的情况下。

    【讨论】:

      【解决方案2】:

      使用LEFT JOINs(我改变了你的连接顺序并修复了 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 *,而是命名您感兴趣的列。

      【讨论】:

        猜你喜欢
        • 2011-09-28
        • 2013-04-25
        • 2013-04-08
        • 1970-01-01
        • 2018-12-16
        • 2011-03-17
        • 2012-09-09
        • 2019-02-07
        相关资源
        最近更新 更多