简体   繁体   中英

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

  • Songs
  • Videos
  • Posts

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM