So I currently got this query:
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
is the current id of the expertise and $_SESSION["user"]["location"]["location_id"]
is the current location id retrieved from the session. For the sake of this example let's say $exid = 3981
and $_SESSION["user"]["location"]["location_id"] = 24
.
I want to retrieve only the users that do not have the expertise_id
of $exid (3981)
attached to them. The current problem is that users that have this id attached to them get displayed when they also got another one attached to them. Let's say that user with user_id
22
has 3981
and 6523
. In this case I don't want him to be part of the results but he is. At first he isn't selected because he has 3981
attached to him but then he is selected because he also has 6523
attached to him.
Update: so I got a little mad from the code used to perform the queries and reworked one of them in a new one so I can pass in a complete query string. Now I can try all of your ideas without getting a headache.
Try this:
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
You can apply conditions to tables directly, no need to put conditions on joined result. It is also way more readable.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.