我有以下查询选择我需要的大部分信息:
SELECT cm.*, companies.company_name, companies.permalink,last_met.*,(cm.total_unique_visitors - last_met.last_UV)/last_met.last_UV * 100 as percent_change FROM calculated_metrics as cm
LEFT JOIN companies ON companies.company_id = cm.company_id
LEFT JOIN (SELECT company_id,total_unique_visitors as last_UV FROM calculated_metrics WHERE MONTH(date) = '04' AND YEAR(date) = '2011' GROUP BY company_id) last_met ON cm.company_id = last_met.company_id
WHERE MONTH(cm.date) = '05' AND YEAR(cm.date) = '2011'
AND cm.total_unique_visitors >3000
AND cm.total_unique_visitors<9999999
ORDER BY percent_change DESC
我现在被要求对数据进行更多排序。我需要按2个表(marketing_strategy和product_type)对数据进行排序。 这些表都包含company_id和每个公司的多个记录 的 实施例
marketing_strategy (表)
company_id marketing_strategy_option_id
605 25
605 9
604 21
604 9
product_type (表)
company_id product_type_option_id
605 12
605 13
604 13
604 3
使用这两个表和上面的查询进行排序的最佳方法是什么?
我将为marketing_strategy选项和product_type选项提供逗号分隔的字符串。
(例如marketing_strategy:25,9 product_type:13,3)
通过使用PHP然后只选择包含特定marketing_strategy和product_type id的公司,可以更容易地运行上面的循环查询吗?
我在这里不知所措。
答案 0 :(得分:0)
我想我可能已回答了我自己的问题。阅读SO我找到了我要找的东西:
Multiple Where conditions on same column
到目前为止,查询正在按预期工作。
SELECT cm.*, companies.company_name, companies.permalink,last_met.*,company_type_options_id,company_marketing_options_id,(cm.total_unique_visitors - last_met.last_UV)/last_met.last_UV * 100 as percent_change FROM calculated_metrics as cm
LEFT JOIN companies ON companies.company_id = cm.company_id
LEFT JOIN (SELECT company_id,total_unique_visitors as last_UV FROM calculated_metrics WHERE MONTH(date) = '4' AND YEAR(date) = '2011' GROUP BY company_id) last_met ON cm.company_id = last_met.company_id
LEFT JOIN company_marketing_strategy ON cm.company_id = company_marketing_strategy.company_id
LEFT JOIN company_type ON cm.company_id = company_type.company_id
WHERE MONTH(cm.date) = '05' AND YEAR(cm.date) = '2011'
AND company_marketing_options_id IN (25,21)
AND company_type_options_id IN (3)
AND cm.total_unique_visitors >3000
AND cm.total_unique_visitors<9999999999
GROUP BY cm.company_id
HAVING COUNT(DISTINCT company_marketing_options_id) = 2
AND COUNT(DISTINCT company_type_options_id) = 1
ORDER BY percent_change DESC