我有几个(MySQL)表。有趣的是CampaignRegion
存储Campaign
的外键和City
,County
,District
,{{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
本身或Campaigns
或City
或County
匹配的District
或State
的{{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
做什么?这个查询位于SELECT
或Campaign
?你怎么看?
感谢您的帮助。
答案 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;