开发者

Confused in mysql query

开发者 https://www.devze.com 2023-02-13 11:24 出处:网络
I have two tables property_description and property_extras. Table property_description looks like id location price etc etc

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

开发者_如何学JAVA
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,'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号