This is my question: I have 3 tables:
USERS
USERS_INFO
COMPANIES_INFO
The USERS
table has a field ID
The tables USERS_INFO
and COMPANIES_INFO
have a field ID_USER
that is linked by a foreign key with ID
.
The question is, how can I select a row that is present in just one of them?
An example:
USERS
+----+
| id |
+----+
| 1 |
+----+
| 2 |
+----+
USERS_INFO
+---------+---------+
| id_user | name |
+---------+---------+
| 1 | Jhonny |
+---------+---------+
COMPANIES_INFO
+---------+---------+
| id_user | company |
+---------+---------+
| 2 | Apple |
+---------+---------+
What I want is something like this:
SELECT * FROM users_info, companies_info WHERE id_user=2
And get this:
id_user = 2
company = Apple
Instead if I did
SELECT * FROM users_info, companies_info WHERE id_user=1
I would have got:
id_user =1
name = Jhonny
I want for example select the user 2, by checking both tables USERS_INFO
and COMPANIES_INFO
because we don't know which one contains it... Any help?
Try this:
SELECT U.id
FROM users U
LEFT JOIN users_info UI ON U.id = CI.id_user
LEFT JOIN companies_info CI ON U.id = CI.id_user
WHERE UI.id IS NOT NULL AND CI.id IS NOT NULL
You can try this:
SET @user = 1;
SELECT id_user, name FROM USERS_INFO WHERE id_user = @user
UNION
SELECT id_user, company as name FROM COMPANIES_INFO WHERE id_user = @user;
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.