左加入哪里

时间:2014-10-15 20:25:31

标签: php mysql left-join

$ i table:id,item_name

$ t table:id,member_name,item_name

$ u table:id,member_name,membership_status

我想

  1. 列出$ i中的所有item_names,即使$ t表中没有任何项目名称
  2. 加上$ t
  3. 中的item_names数
  4. 然后将计数结果限制为$ u。中的membership_status ='active'。
  5. 这是我到目前为止所回答的问题的第一部分:

    $find_actives = mysql_query ("select $i.item_name,  
                      count($t.item_name) from $i left  
                      join $t on $i.item_name = $t.item_name group by $t.item_name")
    

    但是当我将其更改为下面的查询时,它不再列出$ i中的所有项目。

    $find_actives = mysql_query ("select $i.item_name,  
                      count($t.item_name) from $i left  
                      join $t on $i.item_name = $t.item_name 
                      where $t.member_name IN (select distinct member_name from $u
                      where membership_status = 'active' group by member_name)
                      group by $t.item_name")
    

    我希望结果如下:

    item_name1 - count = 5

    item_name2 - count = 0 //这是缺失的行

    item_name3 - count = 2

    我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

如果我正确地阅读你的问题,我认为这就是你要找的:

SELECT
    $i.item_name,
    COUNT(temp.item_name) AS item_count
FROM $i
LEFT JOIN (
    SELECT $t.item_name AS item_name
    FROM $t
    INNER JOIN $u
      ON $t.member_name = $u.member_name
    WHERE $u.membership_status = 'active'
) AS temp
  ON $i.item_name = temp.item_name
GROUP BY $i.item_name