【问题标题】:Getting a corresponding and non corresponding values from many to many table从多对多表中获取对应和不对应的值
【发布时间】:2016-06-10 11:48:14
【问题描述】:

我有一个如下表结构:

品牌 => 历史

History 是多对多表,包含以下值:

brandId, userId and points

我需要获取所有具有 USER SCORED 分数的品牌,以及用户没有相应价值的所有品牌。它看起来像这样:

brandId => 1 (has corresponding value) => 5 points
brandId => 2 (no corresponding value) => null (column points is null)

等等……

有人可以帮我解决这个问题吗?

编辑:

您好 Gordon,我已将您的查询修改为如下所示:

select b.*, sum(h.points) as points
from brands b left join
     histories h
     on b.id = h.brandId 
     and h.userId = 2866 and h.brandId = 2
group by h.brandId

我需要第二个条件 h.brandID = 2 // 或其他一些值,以便一次只返回 1 条记录,如果没有记录,我希望列点为空,如果它isnt ,它应该总结所有的点 n 在列中显示它们...

【问题讨论】:

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


    【解决方案1】:

    我想你只想要一个left joingroup by

    select b.brandId, sum(h.points)
    from brands b left join
         histories h
         on b.brandid = h.brandid and h.userId = $userId
    group by b.brandId;
    

    如果histories 中没有用户的行,则值为NULL

    编辑:

    如果您使用的是left join,那么group by 应该位于第一个表的列中:

    select b.*, sum(h.points) as points
    from brands b left join
         histories h
         on b.id = h.brandId and
            h.userId = 2866 and h.brandId = 2
    group by b.brandId;
    

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2012-10-31
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多