[英]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.