SQL JOIN:带有表名的前缀字段

时间:2015-10-27 09:40:04

标签: mysql sql

我有以下表格

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)
);

使用以下数据:

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);

我希望获得所有组的所有约束,因此我执行以下操作:

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

得到以下结果:

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

我想得到的内容:

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

这是一个示例,在我的实际情况中,我的表格中包含更多列,因此使用SELECT groups.name as group_name, ...会导致查询很难维护。

3 个答案:

答案 0 :(得分:1)

试试这种方式

    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

答案 1 :(得分:0)

issue

可能重复

答案 2 :(得分:0)

我看到的唯一区别是列的名称?用于ASther声明。

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

此外,更好的连接构造是:

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;