如何连接3个表并从MySql中的一个表中总计列?

时间:2013-06-06 10:21:11

标签: mysql

我有3张桌子。 (例如,我最初采用的是一些简短的名字)

  1. table1 as 1
  2. table2 as 2
  3. table3 as 3
  4. block_id是所有三个表的连接属性

    注释:

    • block_id是唯一的,table1
    • 中存在block_status
    • table2
    • 中存在重复的block_id,thickness_id,no_of_slabs
    • 表3中存在重复的block_id,sub_block_id,p_status

    我想显示block_id,slab的总​​数,各个block_id的p_status,其中status ='cut'

    • 我们可以通过block_id
    • 获取从表格中获得的总楼数
    • 如果所有sub_block_id的状态都已完成,那么z_status = FullyCompleted else partialCompleted。

    我已经尝试了以下查询,但它不起作用,

    select 1.block_id,sum(2.noofslabs) as totalslabs,if(3.status='completed','fullyCompleted','partiallyCompleted') from table1 as 1 
    left join table2 as 2 on 1.block_id=2.block_id 
    left join table3 as 3 on 1.block_id=3.block_id where 1.status='Cut'
    

    如果我没有添加table3,则totalslabs的结果是正确的,如果我添加连接table3,结果是错误的。 还有一件事是如何将z_status作为部分完成或完全完成

1 个答案:

答案 0 :(得分:0)

您不能将数字用作表别名。使用以字母开头的名称。

select t1.block_id,sum(t2.noofslabs) as totalslabs,if(t3.status='completed','fullyCompleted','partiallyCompleted') from table1 as t1 
left join table2 as t2 on t1.block_id=t2.block_id 
left join table3 as t3 on t1.block_id=t3.block_id where t1.status='Cut'

应该有效