带case / COALESCE语句的SQL查询

时间:2013-05-21 12:28:27

标签: mysql

我有完美的工作查询。但现在有情况我必须在case语句中加入2查询。但问题是其中一个查询已经在使用。所以我的问题如何在一个中添加这两个sql SQL

我原来的sql是

SELECT
tc.dentist_id,md.vendor_no,pl.pack_trans_id,tc.agent_dentist,md.company_name,md.contact,md.phone_no,sql1.image_path,sql1.metal_id,sql1.expect_more,sql1.how_long_acquire,tc.check_amt,tc.check_date_sent,tc.check_no
          FROM tbl_check tc
          LEFT JOIN tbl_mst_dentist md ON tc.dentist_id=md.dentist_id
          LEFT JOIN tbl_pack_list pl   ON tc.pack_id=pl.pack_id 
          LEFT JOIN (SELECT image_path,pack_id,metal_id,expect_more,how_long_acquire FROM
tbl_metals_list  GROUP BY  pack_id
          )sql1 ON tc.pack_id=sql1.pack_id
          WHERE tc.sale_agent_id = '3' AND tc.paying_percent !=0 

现在我必须在上面的语句中添加2个sql语句

if(tc.agent_dentist=a) select sa.* ,sm.state_code from tbl_sales_agent
as sa,tbl_mst_state as sm where sa.sales_agent_id = '3' AND
sa.state=sm.state_name else select * from tbl_mst_dentist where
dentist_id =tc.dentist_id

第二张表已经在使用中。是否可能?提前致谢

2 个答案:

答案 0 :(得分:1)

是的,您可以使用具有不同名称的ALIAS。例如。表ASYYALALAS。

SELECT *
FROM t1
JOIN t2 AS alias_a ON (alias_a.t1_id = t1.id)
JOIN t2 AS alias_b ON (alias_b.t1_id = t1.id)

答案 1 :(得分:0)

请注意,在没有任何聚合函数的情况下,在此查询中使用GROUP BY ...

   SELECT image_path
        , pack_id
        , metal_id
        , expect_more
        , how_long_acquire 
     FROM tbl_metals_list  
    GROUP 
       BY  pack_id

......没什么意义。也许你的意思是SELECT DISTINCT ......?