2016-10-25 22 views
0

所以我目前得到這個查詢:MySQL查詢到從關係表中檢索數據並篩選出重複

SELECT user_expertise.user_id, user_expertise.expertise_id 
FROM user_expertise 
INNER JOIN user_locations ON user_expertise.user_id = user_locations.user_id 
WHERE user_expertise.expertise_id!=$exid AND user_locations.location_id = $_SESSION["user"]["location"]["location_id"] 
ORDER BY user_expertise.user_id 

$exid是專業知識的電流id和$_SESSION["user"]["location"]["location_id"]是從會話檢索到的當前位置標識。爲了這個例子,我們假設$exid = 3981$_SESSION["user"]["location"]["location_id"] = 24

我想只檢索附加到它們的沒有expertise_id$exid (3981)的用戶。目前的問題是,附有此ID的用戶在他們還附加了另一個用戶時會顯示出來。假設用戶user_id2239816523。在這種情況下,我不希望他成爲結果的一部分,但他是。起初他沒有被選中,因爲他有附加在他身上的3981,但隨後他被選中,因爲他也附有6523

更新:所以我對用於執行查詢的代碼感到有些生氣,並在新的代碼中重寫了其中的一個,因此我可以傳入完整的查詢字符串。現在我可以嘗試所有的想法而不會感到頭疼。

+1

我對你的總體建議是學習如何在PHP中使用例如mysqli或PDO庫來準備sql語句。你現在看起來像意大利麪條低質量的代碼。 – Jacobian

+0

你的命名很混亂。 '$ exid'(eww)是「Expertise ID」的簡稱,但您將其與名爲'user_id'的字段進行比較。這是什麼?我想我們的代碼命名是第一步,然後使用不同的'JOIN'或者添加'WHERE事件NOT IN(SELECT thing FROM other_thing)'類型的子查詢。 – moopet

+0

對不起moopet,應該是expertise_id。當我複製代碼時發生錯誤 –

回答

0

試試這個:

SELECT p.user_id, p.expertise_id FROM (
    SELECT s.user_id, s.expertise_id,t.expertise_id, 
      CASE WHEN s.expertise_id = t.expertise_id THEN 1 ELSE 0 as ind 
    FROM user_expertise s 
    INNER JOIN user_locations ss ON s.user_id = ss.user_id 
    CROSS JOIN user_expertise t 
    WHERE t.user_id = $exid 
     AND s.user_id <> t.user_id 
     AND ss.location_id = $_SESSION["user"]["location"]["location_id"]) p 
GROUP BY p.user_id, p.expertise_id 
HAVING MAX(p.ind) = 0 
0

您可以申請條件表直接,沒有必要把對加入結果的條件。它也更可讀。

SELECT user_expertise.user_id, user_expertise.expertise_id 
FROM user_expertise 
WHERE 1=1 
AND user_expertise.user_id NOT IN 
    (SELECT user_id FROM user_expertise WHERE expertise_id=$exid) 
AND user_expertise.user_id IN 
    (SELECT user_id from user_locations where location_id = $_SESSION["user"]["location"]["location_id"]) 
ORDER BY user_expertise.user_id