简体   繁体   中英

How to implement a search query across two tables?

I'm implementing a very simple search function for my webpage. There is a table name tasks that has 4 columns of interest: name, descritption, status (last one is a multiple choice with three possible choices) and username.

So I do the search like this:

SELECT * FROM tasks WHERE ((description LIKE '%search_val%' OR name LIKE '%search_val%') AND status='selected_status')

For all intents and purposes this works. However now I realized that I want the search pattern entered by the user (the above sentence is executed in PHP code) to also be able to search in the columns name and lastname of a different table: table users. If there is a task for the username (the field common to both tables) then also be a result of the query.

So say, a user enters John in the search box. I want to show any tasks with a username with a user that has John as a lastname or first name AND show me any tasks that contain John in the description or task name.

How would I write the query for this?

Use a JOIN to connect the users and tasks tables, and combine the two queries with UNION

SELECT *
FROM tasks
WHERE description LIKE '%search_val%' OR name LIKE '%search_val%'

UNION

SELECT t.*
FROM tasks AS t
JOIN users AS u ON t.username = u.username
WHERE u.name LIKE '%search_val%' OR u.lastname LIKE '%search_val%'

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