0

这是我的问题:我有 3 张桌子:

USERS

USERS_INFO

COMPANIES_INFO

USERS表有一个字段IDUSERS_INFOCOMPANIES_INFO有一个ID_USER由外键链接的字段ID

问题是,我如何选择其中一个中存在的行?

一个例子:

USERS
+----+
| id |
+----+
| 1  | 
+----+
| 2  | 
+----+

USERS_INFO
+---------+---------+
| id_user | name    |
+---------+---------+
| 1       | Jhonny  |
+---------+---------+


COMPANIES_INFO
+---------+---------+
| id_user | company |
+---------+---------+
| 2       | Apple   |
+---------+---------+

我想要的是这样的:

SELECT * FROM users_info, companies_info WHERE id_user=2

得到这个:

id_user = 2
company = Apple

相反,如果我这样做了

SELECT * FROM users_info, companies_info WHERE id_user=1

我会得到:

id_user =1
name = Jhonny

例如,我想通过检查两个表来选择用户 2,USERS_INFO因为COMPANIES_INFO我们不知道哪一个包含它......有什么帮助吗?

4

2 回答 2

0

尝试这个:

     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
于 2013-07-29T07:35:00.167 回答
0

你可以试试这个:

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;
于 2013-07-29T08:43:31.720 回答