如何将表连接到此SQL代码?

时间:2011-03-23 00:32:21

标签: php mysql sql loops join

我正在使用来自 @Richard aka cyberkiwi 的这个非常棒的代码来运行查询(它为每个工厂返回每个月value的总和):

表名:数据

record_id   id_fk    plant_id_fk    date         value   category_1
1           1          1            2011-03-01   10      A
2           1          1            2011-03-02   10      A
3           1          1            2011-04-10   5       B
4           1          2            2011-04-15   5       C

SQL代码

    select up.id_fk, up.plant_id_fk, ym2, ifnull(sum(data.value_1),0) totalvalue_1
    from (select distinct date_format(date, '%Y-%m') ym, date_format(date, '%M %Y') ym2 from data) dates
    cross join (select distinct data.id_fk, data.plant_id_fk from data) up
    left join data on date_format(data.date, '%Y-%m') = dates.ym
        and up.id_fk=data.id_fk
        and up.plant_id_fk=data.plant_id_fk
        and category_1='A'
    group by up.id_fk, up.plant_id_fk, ym2, ym
    order by up.id_fk, up.plant_id_fk, date(concat(ym,'-1'))

现在我需要将这个与下表联系起来,以便运行一个PHP循环来检索plant_name而不是plant_id

表名:植物

id_fk    plant_id      plant_name
1        1             oak tree
1        2             cherry tree

任何人都知道在哪里插入会创建此连接的子句?

谢谢!

3 个答案:

答案 0 :(得分:3)

修改如下图所示

  

选择
       up.id_fk,
       的 p.plant_name,
       YM2,
       ifnull(sum(data.value_1),0)totalvalue_1
      来自(
       选择不同的date_format(日期,'%Y-%m')ym,date_format(日期,'%M%Y')ym2
       来自数据)日期
      交叉加入(
       选择不同的data.id_fk,data.plant_id_fk
       来自数据)上       内部联接植物p on p.plant_id = up.plant_id_fk
      左连接数据
        on date_format(data.date,'%Y-%m')= dates.ym
        和up.id_fk = data.id_fk
        和up.plant_id_fk = data.plant_id_fk
        和category_1 ='A'
      group by up.id_fk,up.plant_id_fk,ym2,ym, p.plant_name
      按up.id_fk,up.plant_id_fk,date(concat(ym,' - 1'))订购

答案 1 :(得分:1)

嗯。我不认为记录集和查询是匹配的;我没有看到字段集中的字段record_id。我会调整您提供的查询。

select up.id_fk, up.plant_id_fk, pn.plant_name, ym2, ifnull(sum(data.value_1),0) totalvalue_1
    from (select distinct date_format(date, '%Y-%m') ym, date_format(date, '%M %Y') ym2 from data) dates
    cross join (select distinct data.id_fk, data.plant_id_fk from data) up
    left join data on date_format(data.date, '%Y-%m') = dates.ym
        and up.id_fk=data.id_fk
        and up.plant_id_fk=data.plant_id_fk
        and category_1='A'
    INNER JOIN plants pn ON up.plant_id_fk = pn.plant_id
    group by up.id_fk, up.plant_id_fk, ym2, ym
    order by up.id_fk, up.plant_id_fk, date(concat(ym,'-1'))

这应该有效。我将pn.plant_name添加到SELECT区域,并使用INNER JOIN将plants表连接到字段plant_id_fk的up选择。

顺便说一句,如果SQL元素大写(SELECT,JOIN,GROUP等)以及表定义(UP,YM2,YM,DATES等),它会更容易阅读。这只是我个人的偏好。

尼山卡拉西克 www.medfocusrcm.com

答案 2 :(得分:0)

在小组之前

left join plants on data.id_fk=plants.id_fk and data.plant_id_fk=plants.plant_id

然后在group by中替换并选择{up.id_fk,up.plant_id_fk} by plant.plant_name