代码之家  ›  专栏  ›  技术社区  ›  TigerTiger

关键字搜索、多表、PHP和Mysql,使用哪种连接?

  •  1
  • TigerTiger  · 技术社区  · 17 年前

    我有3张表事件、位置、事件位置。事件可以有多个位置。 位置表有纬度、经度和地理代码字段。

    因此,对于关键字“hello world”

    对Event表的简单查询变为

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

    但是,如果用户已经输入了他们的位置,那么我也想在这个查询中包含位置表,这样用户就可以指定他们选择的位置,我该怎么做?

    所以基本上有三种类型的搜索查询

    • 只是关键字

    • 关键字和位置

    • 关键词、邻近度和位置

       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
    

    内部链接意味着活动必须有一个或多个地点。如果一个事件没有任何位置,它就不会出现在搜索结果中。请帮帮我,我该怎么做?

    谢谢你的帮助。

    2 回复  |  直到 17 年前
        1
  •  2
  •   Tomalak    17 年前

    你的连接语法都搞砸了。在任何情况下,如果内部连接没有切割它,请使用外部连接。 ;-)

    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
  •  1
  •   Vinko Vrsalovic    17 年前

    使用 LEFT JOIN

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

    推荐文章