从多个表中选择子查询的连接

时间:2014-02-13 00:06:58

标签: mysql select join

我的选择查询的现有代码

表命名材料:

mat_id       mat_name    supplier_id   stock_in       stock_released    Balance         date
1             alloy         4          30                0               30           feb13
2             steel         2          15                0               15           feb13
3             alloy         2          0                 3               15           feb14

    SELECT m.`mat_id`, m.`mat_name`, m.`stock_in`, m.`stock_released`,
           (select sum(stock_in) - sum(stock_released)
            from material m2
            where m2.mat_name = m.mat_name and
                  m2.mat_id <= m.mat_id
           ) as balance,
          m.`date`
    FROM `material` m
    ORDER BY m.`mat_id` ASC;

如何在供应商表格中添加供应商名称?如何加入这个?

sup_id      sup_name
2             rain
4             george

1 个答案:

答案 0 :(得分:0)

试试这个SQL:

SELECT m.`mat_id`, m.`mat_name`, m.`stock_in`, m.`stock_released`,
       (select sum(stock_in) - sum(stock_released)
        from material m2
        where m2.mat_name = m.mat_name and
              m2.mat_id <= m.mat_id
       ) as balance,
      m.`date`,
      s.`sup_name`
FROM `material` m
LEFT JOIN `supplier` s on s.sup_id = m.supplier_id
ORDER BY m.`mat_id` ASC;