Confused in mysql query
I have two tables property_description
and property_extras
.
Table property_description
looks like
id location price etc etc
1 New York 3000 v v
Table property_extras
looks like
property_id extras
1 12,14,16,167
Well the question is how should mysql query it look to return result only if at least one of extras is matched ?
While it is possible using the schema as it stands, the right way to solve the problem is to normalize your database
You should ideally have extras normalized like
property_id extra_id
1 12
1 14
...
If you can't convert your database structure into something like this, then you have to do something (terrible) like:
SELECT property_id FROM property_extras WHERE
extras LIKE '12,%' OR extras LIKE '%,12,%' OR extras LIKE '%,12'
Or, If you can insert commas to the start and to the end like ,12,14,...,
as delphist points out, simply:
SELECT property_id FROM property_extras WHERE extras LIKE '%,12,%'
Can you fill every extras
row with ,
at start and end of the line (e.g. ,12,14,16,167,
)?
Then this will work perfectly
SELECT FROM `property_description` LEFT JOIN `property_extras` WHERE `property_extras`.`extras` REGEXP ',(13|14|166),'
or
SELECT FROM `property_description` LEFT JOIN `property_extras` WHERE `property_extras`.`extras` REGEXP ',14,'
精彩评论