Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mysql Query using Variable and Inner Join is not returning the correct result

I am quite new to MySQL and i wanted to write a query for my MariaDB database. I have a user and a Contacts table. The contacts table contains two foreign keys and the user table contains an email and a user id. What i want to do is return the emails and the id of all contacts of a given user Id. I used the variable because the id of the user we are searching for can be the first or second id in a contact relation.

The following

SELECT id,
       email,
       @use := IF(first_id = 25, second_id, first_id)
FROM   contacts
       INNER JOIN user
               ON @use = user.id
WHERE  first_id = 25
        OR second_id = 25;  

25 is the user id in this case and this query is returning the following result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+----+-------------------------+-------------------------------------------+
| id | email                   | @use:= IF(first_id=25,second_id,first_id) |
+----+-------------------------+-------------------------------------------+
| 23 | secretemail@gmail.com   |                                        23 |
| 23 | best.secretem@yahoo.com |                                        24 |
| 24 | wow.spa@web.de          |                                        23 |
+----+-------------------------+-------------------------------------------+

What confusing to me is, that the ids do not match when using the inner join. Thanks in advance!

>Solution :

You can use IN () to match with multiple columns.

SELECT u.id,
       u.email
FROM contacts AS c
INNER JOIN user AS u ON user.id IN (c.first_id, c.second_id)
WHERE 25 IN (c.first_id, c.second_id) 
  AND u.id != 25 -- don't return the user whose contact are being listed
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading