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

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

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

    我有三张表:事件、位置、事件位置。事件可以有多个位置。 位置表包含纬度、经度和地理编码字段。

    对事件表的简单查询变成

    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
    

    谢谢你的帮助。

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

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

    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    15 年前

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

    这样,您将为没有位置的事件获取空值。

    另外,尽量不要使用select*,而是命名您感兴趣的列。