0

I want to create a search bar in python. The search bar will search records from table of MySQL database. Table has 9 fields. I want that search bar searches from all the 9 fields and show the result. But I can use only 2 fields at most.

command = "SELECT * FROM table WHERE field1 or field2 LIKE '%PARAM%"

I Want something like this...

command = "SELECT * FROM table WHERE field1 or field2 or field3 or field4 or field5 LIKE '%PARAM%"

But multiple or's are not supported in SQL commands

So is there any way I can search from every field using LIKE Operator

4
  • 1
    Field1 like '%' OR field2 like '%' OR... ... Use SQL parameter to not repeat Commented Jun 24, 2021 at 8:44
  • 1
    The request you are asking for above is not too common in SQL. Having the need to check for the same value across so many might indicate a design smell. You may include your table definition above if you wish. Commented Jun 24, 2021 at 8:45
  • 1
    @TimBiegeleisen it makes sense as a 'free text search' across multiple fields. Commented Jun 24, 2021 at 8:45
  • I'm worried about the possibility of SQL injection in this scenario, make sure you take it into account! Commented Jun 24, 2021 at 8:52

1 Answer 1

1

You could just concatenate them

command = "SELECT * FROM table WHERE concat(field1, field2, field3, field4, field5) LIKE '%PARAM%"

You may want to join them with some separator to reduce the possibility of collisions.

command = "SELECT * FROM table WHERE concat_ws('|', field1, field2, field3, field4, field5) LIKE '%PARAM%"
Sign up to request clarification or add additional context in comments.

2 Comments

Field1 ends with 'pro' and field2 starts with 'blem' and we are searching for 'problem' and we have problem... Edit: not with edited
@Selvin see edit. it still fails for 'PROB|LEM' = 'PROB','LEM', but For a search bar I don't think this would normally need to be 100%... call it a feature!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.