I got a scenario where i got a table with Events(header, description) and a table with Tags(tag, event_id) that contains tags that are linked to each Event.
What I would like to do is to be able to search for a specific word in the Events-table and at the same time search for the word in the Tags-table and get the Events that was found.
I'm abled to search the events with the following SQL
"SELECT events.* FROM events WHERE (header = 'query')"
But when I try to include the tags with a join I get nothing in return
"SELECT events.* FROM events INNER JOIN tags ON tags.events_id =
events.id AND WHERE (events.header = 'query' OR tags.tag = 'query')"
Is there some other way in which I can perform the join or do I开发者_高级运维 need to perform two queries, one for the events and one getting the events which got a matching tag?
Thanks!
Remove the AND
before WHERE
SELECT events.*
FROM events INNER JOIN tags ON tags.events_id = events.id -- NO AND
WHERE (events.header = 'query' OR tags.tag = 'query')
SELECT
events.*
FROM
events
LEFT JOIN
tags
ON
tags.events_id = events.id
WHERE
tags.tag = 'query' OR
events.header = 'query'
or this:
SELECT
events.*
FROM
events,
tags
WHERE
events.id = tags.events_id AND
events.header = 'query' AND
tags.tag = 'query'
But if what you meant was to return the event if the query was found in event.header
or tags.tag
, then use the latter and replace AND
with OR
EDIT:
I forgot to include the events.id = tags.events_id
statement
Perhaps something like this:
SELECT
events.*
FROM
events RIGHT OUTER JOIN tags ON events.id = tags.events_id
WHERE
events.header = 'query' OR
tags.tag = 'query'
精彩评论