0

我有几个(MySQL)表。有趣的是CampaignRegion它存储一个外键到 aCampaign和一个外键到a CityCountyDistrict或。始终只有一个特定于位置的外键集,其他的是.StateCountryNULL

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并且需要得到与自身Campaigns匹配的或者匹配的或者匹配的或者匹配的。CityCountyDistrictStateCountryCity

这实际上很容易,我想出了这样的事情:

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;

但是我想得到Campaignssorted 的结果集,它City首先匹配,然后是匹配的County,然后是匹配的District,依此类推(比如OR查询中的顺序。有没有一种简单的方法可以做到这一点?我会根据 a or中的这个查询SELECT对(第一次匹配)做什么?你怎么看?CampaignJOINSUBSELECT

感谢您的帮助。

4

1 回答 1

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;
于 2012-08-06T09:37:40.557 回答