Answer the question
In order to leave comments, you need to log in
Question about joins?
Good afternoon.
There is a table containing contact information of users:
======================================== ==================
User_id | InfoType | Email | phone |
-------------------------------------------------- -------------
1 | 'Email' | '[email protected]' | NULL |
1 | 'phone' | NULL | '1234567'|
================================================= ==========
It is necessary to pull out all the contact information for a user with such a phone number using the phone number filter.
select * from users JOIN contact_info ON users.user_id=contact_info.user_id
WHERE Phone = '1234567'
in such a query, strings with email will not be included in the result. Answer the question
In order to leave comments, you need to log in
But there is no Phone field in the users table, it is in the contact_info table
SELECT * FROM contact_info
INNER JOIN contact_info AS UserPhone ON contact_info.user_id = UserPhone.user_id
WHERE UserPhone.Phone = '1234567'
users
SELECT users.*, contact_info.* FROM contact_info
INNER JOIN contact_info AS UserPhone ON contact_info.user_id = UserPhone.user_id
INNER JOIN users ON users.user_id = UserPhone.user_id
WHERE UserPhone.Phone = '1234567'
===========================
User_id | InfoType | Value |
---------------------------
1 | 'Email' | '[email protected]' |
1 | 'Phone' | '1234567' |
===========================
SELECT users.*, contact_info.* FROM contact_info
INNER JOIN contact_info AS UserPhone ON contact_info.user_id = UserPhone.user_id
INNER JOIN users ON users.user_id = UserPhone.user_id
WHERE UserPhone.InfoType = 'Phone' AND UserPhone.Phone = '1234567'
You can try like this:
select pn.user_id,
MAX(pn.Phone),
MAX(ml.Email)
from contact_info pn
JOIN users
ON users.user_id = pn.user_id
LEFT
JOIN contact_info ml
ON ml.user_id = pn.user_id
AND ml.InfoType = 'Phone'
WHERE pn.user_id.Phone = '1234567'
AND pn.InfoType = 'Email'
GROUP BY pn.user_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question