IggY
IggY

Reputation: 3125

SQL JOIN : Prefix fields with table name

I have the following tables

CREATE TABLE `constraints` (
  `id` int(11),
  `name` varchar(64),
  `type` varchar(64)
);

CREATE TABLE `groups` (
  `id` int(11),
  `name` varchar(64)
);

CREATE TABLE `constraints_to_group` (
  `groupid` int(11),
  `constraintid` int(11)
);

With the following data :

INSERT INTO `groups` (`id`, `name`) VALUES
(1, 'group1'),
(2, 'group2');

INSERT INTO `constraints` (`id`, `name`, `type`) VALUES
(1, 'cons1', 'eq'),
(2, 'cons2', 'inf');

INSERT INTO `constraints_to_group` (`groupid`, `constraintid`) VALUES
(1, 1),
(1, 2),
(2, 2);

I want to get all constraints for all groups, so I do the following :

SELECT groups.*, t.* FROM groups
LEFT JOIN
    (SELECT * FROM constraints
    LEFT JOIN constraints_to_group
    ON constraints.id=constraints_to_group.constraintid) as t
ON t.groupid=groups.id

And get the following result :

id|  name  | id |  name   type   groupid   constraintid   
-----------------------------------------------------
1 | group1 | 1  | cons1 |  eq  | 1       | 1
1 | group1 | 2  | cons2 | inf  | 1       | 2
2 | group2 | 2  | cons2 | inf  | 2       | 2

What I'd like to get :

group_id | group_name | cons_id |  cons_name | cons_type | groupid | constraintid   
-------------------------------------------------------------------------------------
1        | group1     | 1       | cons1      |  eq       | 1       | 1
1        | group1     | 2       | cons2      | inf       | 1       | 2
2        | group2     | 2       | cons2      | inf       | 2       | 2

This is an example, in my real case my tables have much more columns so using the SELECT groups.name as group_name, ... would lead to queries very hard to maintains.

Upvotes: 4

Views: 3633

Answers (2)

user3331966
user3331966

Reputation: 152

The only difference I see are the names of the columns? Use for that mather an AS-statement.

SELECT 
groups.id AS group_id,
groups.name AS group_name,
t.id AS cons_id,
t.name AS cons_name,
t.groupid, t.constraintid
FROM groups
LEFT JOIN
(SELECT * FROM constraints
LEFT JOIN constraints_to_group
ON constraints.id=constraints_to_group.constraintid) as t
ON t.groupid=groups.id

Besides, a better join-construction is:

SELECT G.id AS group_id,
G.name AS group_name,
CG.id AS cons_id,
CG.name AS cons_name,
C.groupid, C.constraintid
FROM constraints_to_group CG
LEFT JOIN constraints C
ON CG.constraintid = C.id
LEFT JOIN groups G
ON CG.groupid = G.id;

Upvotes: 0

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

Try this way

    SELECT groups.id as group_id,  groups.name as group_name ,
          t.id as cons_id,  t.name as cons_name,  t.type as cons_type,
          a.groupid ,  a.constraintid
   FROM constraints_to_group as a
    JOIN groups on groups.id=a.groupid
    JOIN constraints as t on t.id=a.constraintid

Upvotes: 1

Related Questions