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 Joins, but UNION requires the tables to have the same number of columns, while the JOINs seem to work only with 2 tables?? Is it possible to combine UNION and Joins?
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:
Use
UNION ALLinstead ofUNION, becauseUNIONwould eliminate any rows with the same values.The result of a
UNIONhas only one header, the column names are taken from the fistSELECTin the query. So the column name will be “Name” in your case.USINGis just a syntactical simplification forONwhen the joining columns share the same name(s) and occur only once left and right of the join.Table aliases
User AS uor simplyUser usimplify later references in the code.You can
JOINas many tables as you like, this is not limited to two tables. I suspect, what you really want is this:FULL [OUTER] JOINin MySQL. Other RDBMS have that, like PostgreSQL. Read here.I suspect, that’s not what you wanted to begin with and replaced it with a plain
[INNER] JOIN. Read more in the manual here.