我会推荐存储数据的Entity Attribute Value
orEAV
模型。http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model(这是 Wordpress 帖子和帖子元的工作方式)。
所以假设表格如下:
ENTITY_TABLE: (id,title,author,content,date_created,date_modified)
ATTRIBUTE_TABLE: (id, entity_id, akey, avalue)
使用这样的查询:
SELECT e.*,
MAX( IF(m.akey= 'has_ac', m.avalue, 0) ) as 'has_ac',
MAX( IF(m.akey= 'has_garage', m.avalue, 0) ) as 'has_garage',
MAX( IF(m.akey= 'has_fridge', m.avalue, 0) ) as 'has_fridge',
MAX( IF(m.akey= 'latitude', m.avalue, 0) ) as 'latitude',
MAX( IF(m.akey= 'longitude', m.avalue, 0) ) as 'longitude'
FROM ENTITY_TABLE e
JOIN ATTRIBUTE_TABLE m ON e.id = m.entity_id
WHERE has_ac=1
这将选择实体及其相关属性(has_ac、has_garage、has_fridge、纬度和经度),并要求所有选择的实体的 has_ac 等于 1(真)
现在是地理的东西:
SELECT e.*,
MAX( IF(m.akey= 'has_ac', m.avalue, 0) ) as 'has_ac',
MAX( IF(m.akey= 'has_garage', m.avalue, 0) ) as 'has_garage',
MAX( IF(m.akey= 'has_fridge', m.avalue, 0) ) as 'has_fridge',
MAX( IF(m.akey= 'latitude', m.avalue, 0) ) as 'latitude',
MAX( IF(m.akey= 'longitude', m.avalue, 0) ) as 'longitude',
(
3959 *
acos(
cos( radians( MAX( IF(m.akey= 'latitude', m.avalue, 0) ) ) ) *
cos( radians( CUSTOMER_LAT ) ) *
cos( radians( CUSTOMER_LONG ) - radians( MAX( IF(m.akey= 'longitude', m.avalue, 0) ) ) ) +
sin( radians( MAX( IF(m.akey= 'latitude', m.avalue, 0) ) ) ) *
sin( radians( CUSTOMER_LAT ) )
)
) AS distance
FROM ENTITY_TABLE e
JOIN ATTRIBUTE_TABLE m ON e.id = m.entity_id
WHERE has_ac=1
ORDER BY distance ASC