Search code examples
phpmysqlentity-attribute-value

Select the row which have variables in the text field


I have a MySQL table with a text field, lets say the field name is Car. Car's type is text. I have also some variables like name, product number, date, description, address, price, etc.

Now I want to select from that table, only the row which have my variables found in Car field value.

For example, I want to find only the row which match with my variables, and if Car text is the following and if my variables are name = Honda, product number = 4222, date = 20131223, description = very cool, address = Street 59, price = 15000.

<category>Compact car
<name>Honda XxX
<colour>Black
<productnumber>4222
<date>20131223
<code>US
<description>very cool
<address>Street 59
<price>15000
// ...

Then MySQL query will output only this row. And I would like also as second variant, to output the similar rows which have only one variable which do not match, for example if price do not match then is fine.

I am not sure how to do this with MySQL; maybe somebody knows and can help.

I think something like this will work for first variant.

Select * From Car Where Car LIKE "%name%" AND Car LIKE "%productnumber%" AND ....

Maybe somebody knows a better, faster way. For example, is the following better?

SELECT LOCATE("name", Car) AND LOCATE("productnumber", Car)

I must not split car column into several colums, this is a condition


Solution

  • You definitely want to split your car column into several columns (one for each piece of information). Then the query will become straightforward, for example:

    SELECT * FROM _table WHERE name = 'Honda' AND product_number = 4222 ...
    

    ... but given your constaint, you could do something like this:

    SELECT * FROM _table
    WHERE
        car LIKE '<name>Honda XxX' AND
        car LIKE '<productnumber>4222' ...
    

    If you use prepared statements, you might want to use this template query instead:

    ...
    WHERE
        car LIKE CONCAT ('<name>', ?) AND
        car LIKE CONCAT('<productnumber>', ?)...
    

    But allow me to insist: if your application is meant to go in production, and if you are planning to serve more than a handful of users, or if there are more than a handful of records in this table, tell whoever is in charge that this structure is very, very poor. No index can be used, and it will become unusable very soon.