2015-07-04 101 views
1

我是一個菜鳥,並試圖獲得兩個查詢輸出之間的差異。每個查詢創建一個列表。查詢列表>查詢B列表。此外,查詢B輸出是查詢A.減去2個SQL查詢的輸出

查詢A的一個子集:

SELECT first_name, last_name 
FROM users 
WHERE rating <> '6'; 

查詢B:

SELECT DISTINCT first_name, last_name 
FROM users 
JOIN mp_positions 
ON users.id=mp_positions.user_id 
JOIN mps 
ON mps.id=mp_positions.mp_id 
WHERE mps.status_id = '5'; 

任何幫助,將不勝感激。

+1

你可能想要更新你的問題與來自兩個quires和願望輸出的樣本數據 – Jaylen

回答

1

我不能完全確定你的表的結構的,雖然你可能會想嘗試這樣的事:

SELECT first_name, last_name 
FROM users 
WHERE rating <> '6' 
AND users.id 
NOT IN (SELECT DISTINCT first_name, last_name 
      FROM users 
      JOIN mp_positions 
      ON users.id=mp_positions.user_id 
      JOIN mps ON mps.id=mp_positions.mp_id 
      WHERE mps.status_id = '5' 
); 
+0

工作。我做了一個小小的改變,但完全正確。謝謝,丹尼爾! –

+0

@FranciscoCervera - 將它標記爲答案。它將對未來的讀者有用 –

+0

而不是'NOT IN'應該使用'NOT EXISTS'並且'DISTINCT'沒有必要。 –

2

我會用EXCEPT從而

-- It returns rows from Query A which "doesn't exist in" Query B 
SELECT first_name, last_name 
FROM users 
WHERE rating <> '6' 

EXCEPT 

SELECT DISTINCT first_name, last_name 
FROM users 
JOIN mp_positions 
ON users.id=mp_positions.user_id 
JOIN mps 
ON mps.id=mp_positions.mp_id 
WHERE mps.status_id = '5'; 

然後

-- It returns rows from Query B which "doesn't exist in" Query A 
SELECT DISTINCT first_name, last_name 
FROM users 
JOIN mp_positions 
ON users.id=mp_positions.user_id 
JOIN mps 
ON mps.id=mp_positions.mp_id 
WHERE mps.status_id = '5' 

EXCEPT 

SELECT first_name, last_name 
FROM users 
WHERE rating <> '6';