2012-12-12 27 views
2

我有兩個表empmasterallocation。我使用union來執行sql操作,以便從兩個表中獲得結果。 empmasterempid和其他empdetails。表allocation包含來自empmaster作爲forkey密鑰另一個字段被稱爲per_alloc。我需要檢索empdetails其中滿足:不同字段的兩個select查詢的聯合

  1. empmaster.empidallocation.empid

  2. empmaster.empid in allocation.empid and allocation.per_alloc < 100。我用

MySQL查詢是:

select distinct(tbl_empmaster.emp_fname) 
    from tbl_empmaster 
    where tbl_empmaster.emp_id not in(select tbl_allocation.emp_id 
            from tbl_allocation) 
    union 
    select distinct(tbl_empmaster.emp_fname) 
    from tbl_empmaster 
    where tbl_empmaster.emp_id in(select tbl_allocation.emp_id 
           from tbl_allocation 
           group by emp_id 
           having sum(per_alloc) < 100) 

這僅檢索empdetails,說tbl_empmaster.emp_fname,我需要找回sum(per_alloc) from select tbl_allocation!當我嘗試時會出現很多錯誤,請問任何人都可以告訴我正確的方法嗎?

+0

第一句是一個查詢,沒有格式化,好心從 - 我有兩個表! –

回答

1

試試這個:

SELECT DISTINCT em.emp_fname, 0 alloc 
FROM tbl_empmaster em 
WHERE em.emp_id NOT IN(SELECT emp_id FROM tbl_allocation) 
UNION 
SELECT DISTINCT em.emp_fname, SUM(a.per_alloc) alloc 
FROM tbl_empmaster em 
INNER JOIN tbl_allocation a ON em.emp_id = a.emp_id 
GROUP BY a.emp_id 
HAVING SUM(a.per_alloc)<100 
+0

泰山你很多:)它工作得很好:) –

1

好了,從我明白你的問題,我看到兩個問題。

  1. 在第二個select語句的子查詢中有不必要的分組。應該差不多隻寫
    select tbl_allocation.emp_id from tbl_allocation where tbl_allocation.per_alloc<100) *
  2. 並回答了你的question.change第二select語句下面,它應該工作:
    select A.emp_fname, B.per_alloc from tbl_empmaster A join tbl_allocation B using(emp_id) where A.emp_id in(select C.emp_id from tbl_allocation C where C.per_alloc<100))

**假設EMP_ID是主鍵*