基于计数的MySQLi查询2表在30天内形成一个表

时间:2017-06-24 14:44:59

标签: php join mysqli group-by

我遇到查询问题。

我需要从trade_directory收集2家公司,他们的状态为1,并且匹配3个类别。

我想在过去30天内从company_views中选择最少视图的2家公司。

SELECT
    b.id, b.v_date, b.c_id COUNT(b.c_id) AS v_count
    AND b.v_date >= DATE_ADD(NOW(), INTERVAL - 30 DAY) 
FROM
    company_views b
    LEFT JOIN trade_directory v ON v.id = b.c_id
WHERE
    v.cat1 = 'cat'  
    AND v.cat2 = 'rat'  
    AND v.cat3 = 'hat'                          
    AND v.status = '1'
GROUP BY
    b.c_id
ORDER BY
    v_count ASC
LIMIT 2

由于

克里斯

2 个答案:

答案 0 :(得分:1)

您在AND而不是SELECT

中使用WHERE运算符
AND b.v_date >= DATE_ADD(NOW(), INTERVAL - 30 DAY) 

可以试试这段代码

SELECT
    b.id, b.v_date, b.c_id COUNT(b.c_id) AS v_count
FROM
    company_views b
    LEFT JOIN trade_directory v ON v.id = b.c_id
WHERE
    v.cat1 = 'cat'  
    AND v.cat2 = 'rat'  
    AND v.cat3 = 'hat'                          
    AND v.status = '1'
    AND b.v_date >= DATE_ADD(NOW(), INTERVAL - 30 DAY) 
GROUP BY
    b.c_id
ORDER BY
    v_count ASC
LIMIT 2

答案 1 :(得分:0)

我改变了我的方法(使用不同的表格,但这里有什么工作,但它真的很慢

[HttpPost]
        public ActionResult EmailCampaignProcess(FormCollection collection)
        {
            //var userType = Request["userType"];
            //var emailContent = Request["emailContent"];
            //SendSimpleMessage();
            //ViewBag.Message = "Hello " + Request["userType"];


            var Emails = db.Users.Where(d => d.Subscriptions.Any(x => x.Status == true)).Select(u => u.Email).ToArray();


            foreach (Emails as Email) {

                SendSimpleMessage(Email);

            }

        }

如果我能解决速度问题,那么这个问题会很棒。