求一个多表查询的SQL语句?
共涉及到5张表:
t_bd_supcust_info(supcust_no,sup_name)--跟t_pm_sheet_master的supcust_no产生主外键关系
t_sys_customer(branch_no,name)--跟其它表无直接关系,但是它保存的是公司其它,其它记录都是该公司的
t_bd_item_info(item_no,item_name) --跟t_pm_sheet_detail的item_no产生主外键关系          
t_pm_sheet_master(sheet_no,trans_no,supcust_no,oper_date)--跟t_pm_sheet_detail的sheet_no产生主外键关系
t_pm_sheet_detail(flow_id,sheet_no ,item_no,real_qty,valid_price)【主表】
现在要查询到这样的结果:
flow_id,item_no,item_name,supcust_no,sup_name,oper_date,branch_no,name,real_qty,valid_price我写的SQL:
select 
(select trans_no from t_pm_sheet_master m where m.sheet_no=d.sheet_no) TRAN_ID,
(select top 1 branch_no  from t_sys_customer) SUPERMARKET_ID,
(select top 1 [name]  from t_sys_customer) SUPERMARKET_NAME,
(select oper_date    from t_pm_sheet_master m where m.sheet_no=d.sheet_no) IN_DATE,
(select supcust_no from t_pm_sheet_master m where m.sheet_no=d.sheet_no) SUPPLIER_ID,
(select s.sup_name from t_bd_supcust_info s  join t_pm_sheet_master m  on s.supcust_no=m.supcust_no join t_pm_sheet_detail d on m.sheet_no=d.sheet_no) SUPPLIER_NAME,
item_no   MEAT_CODE,
(select item_name from t_bd_item_info  i where i.item_no=d.item_no) MEAT_NAME,
real_qty     WEIGHT,
valid_price  PRICE
from 
t_pm_sheet_detail d
这个有问题,而且过于繁琐!
希望大家能从这个sql中看出我想要表达的意思!希望大家能说说这个SQL语句该怎么写?

解决方案 »

  1.   

    既然t_sys_customer和其他表没有直接关系,那只能单独查了,怎么一起查呢?
    跟其它表无直接关系,但是它保存的是公司其它,其它记录都是该公司的   这句话没看懂。。
      

  2.   

    SELECT 
    b.sheet_no,
    b.flow_id,
    b.item_no,
    d.*,
    b.real_qty,
    b.valid_price,
    e.*FROM t_pm_sheet_master AS a,t_pm_sheet_detail AS b,t_bd_supcust_info AS c ,(SELECT TOP 1 item_name,item_no FROM t_bd_item_info) AS d,(SELECT TOP 1 branch_no,NAME FROM t_sys_customer) AS e
    WHERE a.sheet_no=b.sheet_no AND a.supcust_no=c.supcust_no
      

  3.   

    select
      a.flow_id,a.item_no,d.item_name,
      b.*,d.oper_date,
      max(c.branch_no) as ,max(c.name) as name,
      a.real_qty,a.valid_price
    from
      t_pm_sheet_detail a,
      t_bd_supcust_info b,
      t_sys_customer c,
      t_pm_sheet_master d
    where
      ---关联字段自己写下 
      

  4.   

    select
      a.flow_id,a.item_no,d.item_name,
      b.*,d.oper_date,
      max(c.branch_no) as ,max(c.name) as name,
      a.real_qty,a.valid_price
    from
      t_pm_sheet_detail a,
      t_bd_supcust_info b,
      t_sys_customer c,
      t_pm_sheet_master d
    where a.xx=b.xx and b.xx=c.xx and c.xx=d.xx