mysql使用UNI查询两个表

时间:2013-05-22 12:44:08

标签: mysql

这是我的查询,我无法纠正。

 SELECT a.pack_id
 FROM (
      SELECT pl.pack_id
      FROM tbl_metals_list ml
      LEFT JOIN tbl_pack_list pl ON ml.pack_id = pl.pack_id
      WHERE ml.sale_agent_id = '3' AND pl.current_tab='metals') a
 UNION(
      SELECT pl.pack_id
      FROM tbl_refining tr
      LEFT JOIN tbl_pack_list pl ON tr.pack_id = pl.pack_id
      WHERE tr.sale_agent_id ='3' AND pl.current_tab = 'refining') b

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT pl.pack_id 
FROM tbl_metals_list ml 
LEFT JOIN tbl_pack_list pl ON ml.pack_id = pl.pack_id 
WHERE ml.sale_agent_id = '3' 
  AND pl.current_tab   = 'metals' 
UNION
SELECT pl.pack_id 
FROM tbl_refining tr 
LEFT JOIN tbl_pack_list pl ON tr.pack_id = pl.pack_id 
WHERE tr.sale_agent_id = '3' 
  AND pl.current_tab   = 'refining' 

答案 1 :(得分:0)

试试这个:

SELECT 
    a.pack_id 
FROM (
    SELECT 
        pl.pack_id 
    FROM 
        tbl_metals_list ml 
    LEFT JOIN tbl_pack_list pl 
        ON ml.pack_id = pl.pack_id 
    WHERE 
        ml.sale_agent_id = '3' 
        AND pl.current_tab='metals' 
    UNION ALL
    SELECT 
        pl.pack_id 
    FROM 
        tbl_refining tr 
    LEFT JOIN tbl_pack_list pl 
        ON tr.pack_id = pl.pack_id 
    WHERE 
        tr.sale_agent_id ='3' 
        AND pl.current_tab = 'refining' 
) a 

<强>更新

SELECT 
    a.pack_id ,
    d.company_name
FROM (
    SELECT 
        pl.pack_id 
    FROM 
        tbl_metals_list ml 
    LEFT JOIN tbl_pack_list pl 
        ON ml.pack_id = pl.pack_id 
    WHERE 
        ml.sale_agent_id = '3' 
        AND pl.current_tab='metals' 
    UNION ALL
    SELECT 
        pl.pack_id 
    FROM 
        tbl_pack_list pl
    LEFT JOIN  tbl_refining tr 
        ON tr.pack_id = pl.pack_id 
    WHERE 
        tr.sale_agent_id ='3' 
        AND pl.current_tab = 'refining' 
) a 
INNER JOIN tbl_pack_list_details d
    ON a.pack_id = d.pack_id