【问题标题】:Retrieve corresponding and non corresponding values from many to many table从多对多表中检索对应和不对应的值
【发布时间】:2016-06-10 11:29:57
【问题描述】:

我有如下表结构:

品牌 => 历史

历史记录表包含以下列:

brandId, userId, points(对于每个品牌,用户得分多少分).. 我需要将他在历史表中两个日期之间得分的用户的所有积分相加。

查询将接受 4 个参数:userId、brandId、startDate、endDate... 以下输出类似于:

userId        brandId       points

1               64           155 sum of all points in between two dates specified by the parameter. 

如果 BrandId 的传递值为 = null(即未传递)。如果在该 BrandId 和 UserId 的历史表中没有找到任何数据,查询也应该返回有关品牌和用户的全部数据......我已经在 Zend Framework 2 中编写了自己的查询,但它没有输出我想要的(仅返回实际在历史表中找到的记录)...

看起来像这样:

public function BrandWallBrandsById($userId,$brandId,$startDate,$endDate)
{
    $select = new Select();
    $select->from(array('p' => $this->table), array('id'));
    $select->join(array('b' => 'brands'), 'p.brandId = b.id', array('id','name', 'cover', 'slogan', 'startDate', 'homepage','endDate','active'));
    $select->columns(array(new Expression('SUM(p.points) as points'), "userId", "brandId"));
    $select->order("p.points asc");
    $select->group("p.brandId");
    $where = new Where();
    $where->notEqualTo("p.points", 0);
    $where->notEqualTo("p.type",10);
    $where->equalTo("p.userId", $userId);
    $where->equalTo("p.brandId", $brandId);
    $where->equalTo("b.active",1);
    $where->between("p.time", $startDate, $endDate);
    $select->where($where);
    return $this->historyTable->selectWith($select)->toArray()[0];
}

请注意,查询一次只返回一条记录。我想写一个纯 SQL 语句,因为我认为它可能比这更容易... 有人可以帮帮我吗?

【问题讨论】:

    标签: php mysql sql-server zend-framework zend-framework2


    【解决方案1】:

    这是一个 SQL 语句,可以让你在 SQL Server 中得到你想要的,虽然我不熟悉 zend-framework。

    declare @startDate datetime, @endDate datetime, @userId int = null, @brandId int = null
    set @startDate = '6/1/2016'
    set @endDate = '6/9/2016'
    set @userId = 1      --this can be NULL
    set @brandId = 64    --this can be NULL
    
    select
        userId,
        brandId, 
        sum(points) as points
    from
        historyTable
    where
        (@userId is null or userId = @userId)
        and (@brandId is null or brandId = @brandId)
        and dateColumn >= @startDate
        and dateColumn < dateadd(day,1,@endDate) 
    group by
        userId, brandId
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      相关资源
      最近更新 更多