简体   繁体   中英

MySQL search in multiple columns

Title sounds pretty simple ... the main problem is from wich direction i should query and how to output the results.

Here's a Screenshot with a empty search:

在此处输入图片说明

The clients should always be visible (matching the search query). So here a few examples:

  • Search for project2 should output client2 with project2
  • Search for client2 should output client2 with all projects
  • Search for client3 should output client3

I query for projects and join in the clients like this:

SELECT *
FROM projects AS a
LEFT JOIN clients AS b ON a.client_id = b.id
WHERE a.name LIKE '%$searchString%' OR b.name LIKE '%$searchString%'

After that i query for clients excluding these that are fetched in the query above. Thats the only way (wich i know) to get the clients that don't have any projects.

Is there a statement that can fetch these results in on query? This seems not very elegant to me. Also if i search client2 project1 the system fails.

EDIT: Thanks for the answers so far. I got a lot with full joins that are not possible in mysql. I changed that in the title and tags of the question ... sorry for that. I didn't know anything about full joins and that they are not possible in mysql.

Here is a good visual representation of the different join types in SQL.

Make sure you are using prepared statements, and not directly putting the searchString into the query, as this is how SQL injection attacks occur.

SELECT
  *
FROM
  clients b LEFT OUTER JOIN
  projects AS a ON a.client_id = b.id
WHERE
  a.name LIKE '%$searchString%' OR
  b.name LIKE '%$searchString%'

Do a RIGHT JOIN which will give you all clients regardless of whether or not they have a project and then WHERE a.name IS NULL will give you only clients without projects.

So the whole query looks like

SELECT *
FROM projects AS a
RIGHT JOIN clients AS b ON a.client_id = b.id
WHERE a.name IS NULL

You can write this

    SELECT
      *
    FROM
      clients b FULL OUTER JOIN
      projects AS a ON a.client_id = b.id
    WHERE
      a.name LIKE '%$searchString%' OR
  b.name LIKE '%$searchString%'

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