获取在mysql中连接2个表的计数和总计数

时间:2016-09-15 07:25:20

标签: mysql sql join count

我在MySQL数据库中有两个表:

1

p_code{
    code varchar(10) primary key,
    discount decimal(4,2) not null,
    valid_till date not null,
    daily int not null,
    total int non null,
    max_amount decimal (6, 2) not null
}

2

p_user{
    code varchar(10) not null,
    email varchar(50) not null,
    date date not null,
    primary key (code, email, date),
    foreign key (code) references p_code(code)
}

现在我希望获得code p_code总计email使用email的次数,code今天使用了多少次SELECT pc.discount, pc.valid, pc.daily, pc.total, pc.max_amount, c.tcount, c.count FROM p_code AS pc LEFT JOIN ( SELECT t.code, t.email, t.tcount, p.count FROM ( SELECT code, email, COUNT( email ) AS tcount FROM p_user GROUP BY code, email ) AS t LEFT JOIN ( SELECT code, email, COUNT( email ) AS count FROM p_user WHERE `date` = CURDATE( ) GROUP BY code, email ) AS p ON ( t.code, t.email ) = ( p.code, p.email ) ) AS c ON pc.code = c.code WHERE c.email = ? AND pc.code = ?

的详细信息

我尝试了以下查询:

code

但问题是如果我在表email中没有p_userp_code的任何条目,它就不会返回任何行。

我要求它应该返回tcount的所有列以及countvar app=angular.module('carService',[]); app.factory('Brandtest',function(){ var brand={}; brand.sample=['Bmw','Mercedes','Honda']; return brand; }); app.controller('selectDropdown',['$scope','Brandtest',function($scope,Brandtest){ $scope.a=Brandtest.sample; $scope.checkselection= function(userSelect){ if($scope.userSelect !="" && $scope.userSelect !=undefined){ $scope.msg = $scope.userSelect; } } }]);列的0和0列。

2 个答案:

答案 0 :(得分:1)

我认为您可以通过这种方式简化您的查询,无论如何,您需要将条件放在左边连接的左边连接数据中。

SELECT 
   c.discount, 
   c.valid, 
   c.daily, 
   c.total, 
   c.max_amount, 
   count(u.email) as totalCount,
   sum(case when u.`date` = CURDATE() then 1 else 0 end) as dailyCount
FROM p_code c
LEFT JOIN p_user u on u.code = c.code and u.email = ?
WHERE c.code = ?
GROUP BY c.discount, c.valid, c.daily, c.total, c.max_amount

对于电子邮件中的“过滤器”,您也可以这样做:

WHERE c.code = ? and (u.email is null or u.email = ?)

答案 1 :(得分:0)

您需要使用IFNULL功能。

  

IFNULL(表达式1,表达式2)

     

如果expr1不为NULL,则IFNULL()返回expr1;否则它会返回   表达式2。

您需要修改您的查询,如:

SELECT pc.discount
  , pc.valid
  , pc.daily
  , pc.total
  , pc.max
  , IFNULL(c.tcount, 0) AS tcount
  , IFNULL(c.count, 0) as count
FROM p_code AS pc
...