可以从具有特定信息的两个表中获取数据的Mysql查询

时间:2013-04-10 14:13:23

标签: php mysql

问题在于我的查询。我需要从两个表中选择数据,table1有一个字段类别,它是类别id,table2有字段id,它是类别id。我需要按月选择数据,例如,如果我们选择2月份,我会在选定的时间段内对该表中的所有内容进行计数,并按类别ID进行分组。例如,在table1中的选定月份中,没有类别id = 3,十个从table2获取并使该类别值= 0。如果在table1的March期间是id = 3的类别,则计算具有该类别id的所有值。

我做了一个选择,但它不对。

$query = sprintf("SELECT count(*) as counter, category, (select category from categories where id=leads.category) as categoryname, clientcode , language                   
                  FROM leads   
                  WHERE synced > %s and synced < %s
                  GROUP BY category, clientcode 
               UNION ALL
                  SELECT 0 as counter, id as category, category as categoryname, 0 as clientcode, language  FROM categories WHERE id NOT IN(SELECT category FROM leads)
                  GROUP BY category, clientcode ",$starttime, $endtime ); 

感谢您的帮助,希望您了解我的需求。

很多文字......

我解决了这个问题:

$query = sprintf("SELECT count(*) as counter, category, (select category from categories where id=leads.category) as categoryname, clientcode , language                   
                      FROM leads   
                      WHERE synced > %s and synced < %s
                      GROUP BY category, clientcode 
                   UNION ALL
                      SELECT 0 as counter, id as category, category as categoryname, 0 as clientcode, language  FROM categories WHERE id NOT IN(SELECT category FROM leads WHERE synced > %s and synced < %s)
                      GROUP BY category, clientcode ",$starttime, $endtime, $starttime, $endtime ); 

0 个答案:

没有答案