[英]How to query two from two seperate datatables with different values
How would I query the following? 我将如何查询以下内容?
User.name and Groups.description,
from the User table and Groups table,
where User.id_user = User_Group.id_user, and Groups.id_groups = User_Group.id_groups
I read about UNION
and Join
s, but UNION
requires the tables to have the same number of columns, while the JOIN
s seem to work only with 2 tables?? 我了解了
UNION
和Join
,但是UNION
要求表具有相同数量的列,而JOIN
似乎仅适用于2个表? Is it possible to combine UNION
and Join
s? 是否可以结合
UNION
和Join
?
SELECT User.Name
FROM User
FULL JOIN User_Groups
ON User.Id_user= User_Groups.Id_user
UNION
SELECT Group.Description
FROM Group
FULL JOIN User_Groups
ON Group.Id_group= Groups.Id_group
Would the above code be right?? 上面的代码正确吗?
Try this simplified query: 试试这个简化的查询:
SELECT u.Name
FROM User u
JOIN User_Groups USING (Id_user)
UNION ALL
SELECT g.Description
FROM Group g
JOIN User_Groups USING (Id_group)
Use UNION ALL
instead of UNION
, because UNION
would eliminate any rows with the same values. 使用
UNION ALL
而不是UNION
,因为UNION
会消除具有相同值的任何行。
The result of a UNION
has only one header, the column names are taken from the fist SELECT
in the query. 一个
UNION
的结果只有一个标题,列名取自查询中的第一个SELECT
。 So the column name will be "Name" in your case. 因此,在您的情况下,列名称将为“名称”。
USING
is just a syntactical simplification for ON
when the joining columns share the same name(s) and occur only once left and right of the join. 当连接列共享相同的名称并且仅在连接的左侧和右侧出现一次时,
USING
只是ON
的语法简化。
Table aliases User AS u
or simply User u
simplify later references in the code. 表别名
User AS u
或只是User u
简化了代码中的后续引用。
You can JOIN
as many tables as you like, this is not limited to two tables. 您可以根据需要
JOIN
任意多个表,但不限于两个表。 I suspect, what you really want is this: 我怀疑,您真正想要的是:
SELECT u.Name, g.Description
FROM User u
JOIN User_Groups USING (Id_user)
JOIN Group g USING (Id_group)
FULL [OUTER] JOIN
in MySQL. FULL [OUTER] JOIN
。 Other RDBMS have that, like PostgreSQL. [INNER] JOIN
. [INNER] JOIN
。 Read more in the manual here . Try this also, I think, no need of join. 我认为也可以尝试加入。
SELECT u.name, g.description FROM User u, Groups g, User_Group ug, Groups.id gi
WHERE u.id_user=g.id_user and g.id_groups=ug.id_groups;
Try : 尝试:
SELECT User.Name, Groups.Description
FROM User
JOIN User_Group on User.id_user = User_Group.id_user
JOIN Groups on Groups.id_groups = User_Group.id_groups
or 要么
SELECT User.Name, Groups.Description
FROM User
JOIN User_Group USING (id_user)
JOIN Groups USING (id_groups)
Not sure why you want to use the union
for ? 不确定为什么要使用该
union
吗? (unless you want 1 column - which you didnt specify) (除非您想要1列-您未指定)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.