tosin ezekiel
tosin ezekiel

Reputation: 33

How to search for keyword in three different tables

Good day, i have been trying to do a simple search from three tables, how posdible is that. I have tables like

The songs table has columns like song_title,song_author. The videos table has columns like videos_title,videos_author. While the posts table also have post_title, post_author.

But i want to search a keyword from a search input box in these columns "Song_title,song_author,video_title,video_,author,post_title"

What i tried so far seems to be completely useless which is:

    $query = "(SELECT song_title, song_author, 'song' as type FROM songs WHERE song_title LIKE '%" . $keyword . "%' OR song_author LIKE '%" . $keyword ."%')
 UNION
 (SELECT video_title, video_author, 'video' as type FROM videos WHERE video_title LIKE '%" . $keyword . "%' OR video_author LIKE '%" . $keyword ."%') 
UNION
 (SELECT post_title,'post' as type FROM posts WHERE post_title LIKE '%"')"; 


mysqli_query($connection,$query);

Thank you in anticipation.

Upvotes: 0

Views: 46

Answers (1)

Ildar Akhmetov
Ildar Akhmetov

Reputation: 1431

The SQL query you're possible looking for is:

SELECT * FROM (
SELECT song_title AS title, song_author AS author, 'song' as type FROM songs
UNION
SELECT video_title AS title, video_author AS author, 'video' as type FROM videos
UNION
SELECT post_title AS title, NULL AS author, 'post' as type FROM posts) a
WHERE title LIKE '%'.$keyword.'%' OR author LIKE '%'.$keyword.'%'

Also, please consider two more important notes:

  1. It is VERY unsafe to use something like '%'.$keyword.'%' in queries. Details here.
  2. You might want to retrieve some kind of ids from your tables, to use further.

Upvotes: 1

Related Questions