How can I set up a query to compare all columns in a table with my text
I want to create a query where I can compare all columns in a table with my text and get the results. Something like this,
$query="SELECT * FROM table_name WHERE `column1` LIKE '%text%', `column2`LIKE '%text%开发者_C百科', `column3` LIKE '%text%' ......`columnN` LIKE '%text%'
Helps are appreciated.
You can use a FULLTEXT index:
CREATE FULLTEXT INDEX ON table_name (column1, column2, column3, ... columnN);
SELECT * FROM table_name
WHERE MATCH(column1, column2, column3, ... columnN) AGAINST ('text')
This is not only easier to code, but it can run hundreds of times faster than using wildcard patterns LIKE '%text%'
.
Note you must list the same columns in your MATCH() clause as the columns you specified for the index.
Another suggestion: if the multiple columns (column1, etc.) are really multiple values for the same type of thing, you should put them in a child table.
Re your questions about getting errors:
My apologies, my example above was incomplete. CREATE INDEX
requires that you give the index a name. For example:
CREATE FULLTEXT INDEX ftbeer ON beer (beer, brewery, style, type, aroma,
taste, strength, appearance, origin, rating, price, description);
Also if you use back-ticks, be careful to use them properly, to delimit table names or column names. You seem to have imbalanced back-ticks.
精彩评论