SQL查询SQLSTATE [42S21]:列已存在:1060重复的列名

时间:2019-06-15 10:24:06

标签: php sql laravel

我正在尝试联接3个表,其中1个表具有另外2个表的主键。代码如下:

首先,我尝试不使用任何别名来运行查询。然后更改它。


     public function member_show()
     {
        $number_of_member =
        DB:: table('members')
        ->distinct('email')
        -> count('email');

        $data = DB::select("
          SELECT m.member_id, m.member_name, m.email, m.password,              
          cl.club_name, ct.city_name, jobtype.type_name 
          FROM members as m
          LEFT JOIN clubs as cl ON cl.club_id = m.club_id 
          LEFT JOIN cities as ct ON ct.city_id = m.city_id 
          LEFT JOIN (SELECT * 
          FROM jobs as jb
          LEFT JOIN j_types as jt
          ON jt.type_id = jb.type_id) as jobtype
          ON jobtype.member_id = m.member_id
         ");

        return view('member.show',['num_member' => $number_of_member, 'data'     
        => $data]);
    }

错误是:

   SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name   
   'type_id' (SQL: SELECT m.member_id, m.member_name, m.email, m.password,
   cl.club_name, ct.city_name, jobtype.type_name FROM members as m LEFT JOIN  
   clubs as cl ON cl.club_id = m.club_id LEFT JOIN cities as ct ON
   ct.city_id = m.city_id LEFT JOIN (SELECT * FROM jobs as jb LEFT JOIN j_types
   as jt ON jt.type_id = jb.type_id) as jobtype ON jobtype.member_id = 
   m.member_id    )

2 个答案:

答案 0 :(得分:2)

在内部,type_idj_types表中同时存在jobs,因此您必须选择其中之一。

(SELECT * 
          FROM jobs as jb
          LEFT JOIN j_types as jt
          ON jt.type_id = jb.type_id) as jobtype

更改为以下内容:

(SELECT jb.*, jt.x, jt.y, jt.z
          FROM jobs as jb
          LEFT JOIN j_types as jt
          USING (type_id)) as jobtype

答案 1 :(得分:1)

问题是子查询中的SELECT *返回了FROM中所有表的所有列。至少有一个重复的列名-type_id子句中使用的ON-但也可以有其他重复的列名。

子查询是不必要的。而且,在某些数据库中可能会影响性能。

写出没有不必要子查询的查询:

SELECT m.member_id, m.member_name, m.email, m.password,              
      cl.club_name, ct.city_name, jt.type_name 
FROM members m LEFT JOIN
     clubs cl
     ON cl.club_id = m.club_id LEFT JOIN
     cities ct
     ON ct.city_id = m.city_id LEFT JOIN
     jobs jb
     ON jb.member_id = m.member_id LEFT JOIN
     j_types jt
     ON jt.type_id = jb.type_id;