查找与一个字段匹配的相关实体

时间:2012-08-06 09:32:42

标签: mysql sql join

我有几个(MySQL)表。有趣的是CampaignRegion存储Campaign的外键和CityCountyDistrict,{{1}的外键}或State。始终只有一个特定于位置的外键设置,其他是Country

NULL表如下所示:

CampaignRegion

我现在需要一个查询来选择mysql> describe CampaignRegion; +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | campaign_id | int(11) | YES | MUL | NULL | | | country_id | int(11) | YES | MUL | NULL | | | state_id | int(11) | YES | MUL | NULL | | | district_id | int(11) | YES | MUL | NULL | | | county_id | int(11) | YES | MUL | NULL | | | city_id | int(11) | YES | MUL | NULL | | +-------------+---------+------+-----+---------+----------------+ 。我有Campaign,需要获得与City本身或CampaignsCityCounty匹配的DistrictState的{​​{1}}。

这实际上非常简单,我想出了类似的东西:

Country

但是,我希望得到City的结果集,其排序首先匹配SELECT count(id) as campaign_count, campaign_id FROM CampaignRegion WHERE (city_id = 32076 OR district_id = 127 OR state_id = 7 OR country_id = 156) GROUP BY campaign_id HAVING campaign_count > 0; ,然后匹配Campaigns,然后匹配City的结果集等等(就像查询中County的顺序一样。有没有一种简单的方法可以做到这一点?我会根据District(第一次匹配)OR做什么?这个查询位于SELECTCampaign?你怎么看?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西:

SELECT count(id) as campaign_count, campaign_id
FROM CampaignRegion
WHERE (city_id = 32076 OR district_id = 127 OR state_id = 7 OR country_id = 156)
GROUP BY campaign_id
HAVING campaign_count > 0;
ORDER BY (city_id = 32076) DESC, (country_id = 156) DESC, (state_id = 7) DESC, (district_id = 127) DESC;