views:

1444

answers:

3

Hi

I have 3 tables event, location, event_location. Event can have multiple locations. Location table has lattitude, longitude, hasGeocode fields.

so for keywords "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

  • 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.

+1  A: 

Use LEFT JOINs (I altered the order of your joins and fixed the where clause location, which was misplaced)

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.

Also, try not to use select * but name the columns you are interested in.

Vinko Vrsalovic
+1  A: 

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.

Tomalak
A: 

sir plz show out put (in the form picture) with code or demo

ashwani