Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL JOIN : Prefix fields with table name

Tags:

sql

mysql

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.

like image 857
IggY Avatar asked Sep 24 '26 17:09

IggY


1 Answers

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
like image 123
Mukesh Kalgude Avatar answered Sep 27 '26 07:09

Mukesh Kalgude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!