[英]MYSQL query to retrieve data from a relational table and filter out duplicates
所以我目前得到這個查詢:
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"]
是從會話中檢索到的當前位置ID。 為了這個示例,我們假設$exid = 3981
和$_SESSION["user"]["location"]["location_id"] = 24
。
我想只檢索沒有用戶expertise_id
的$exid (3981)
連接到他們。 當前的問題是,當附加了該ID的用戶同時又附加了一個ID時,就會顯示該用戶。 假設具有user_id
22
用戶具有3981
和6523
。 在這種情況下,我不希望他成為結果的一部分,但他是。 最初,沒有選擇他是因為他擁有3981
,但是后來被選中是因為他還擁有6523
。
更新:所以我對用於執行查詢的代碼有些生氣,並在一個新的代碼中對其中的一個進行了重新編寫,以便可以傳遞完整的查詢字符串。 現在,我可以嘗試所有的想法,而不會頭痛。
嘗試這個:
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
您可以直接將條件應用於表,而無需在連接結果上放置條件。 它也更具可讀性。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.