MySQL-使用当前列数将列添加到临时表

时间:2019-12-13 13:32:46

标签: mysql temporary

有一个具有预定义结构的MySQL临时表定义:

create temporary table TempTableName as
  select tData.id as id,
         tData.name as name
         tData.someData as data,
from SomeTableName tData inner join ...

结果是临时表包含了一些行和一些数据。

如何使用additioanl列进行修改以存储rowNumber? 例如:

id    name    data    num
<id>  <name> <data>   1
<id>  <name> <data>   2
<id>  <name> <data>   3

因此,新的num列应包含当前计数行。如何修改它才能添加这样的计数器?

3 个答案:

答案 0 :(得分:1)

需要使用主键设置AUTO_INCREMENT,因此可以。对您来说,cou可以添加

Genre

答案 1 :(得分:1)

如果您只想添加计数器列,则:


public function store(Request $request)
{

  $this->validate($request, [
      'student_name' => 'required|string|max:255',
      'student_father_name' => 'required|string|max:255',
      'student_mother_name' => 'required|string|max:255',
      'student_photo' => 'required|image|mimes:jpeg,png,jpg|max:2048',  
]);

    $input['student_photo'] = time().'.'.$request->student_photo->getClientOriginalExtension();
    $folder1 = public_path('STUDENT_DATA/STUDENT_PHOTO/');
    $path1 = $folder1 . $input['student_photo']; // path 1
    $request->student_photo->move($folder1, $input['student_photo']); // image saved in first folder
    $path2 = public_path('../../../abc.com/public/STUDENT_DATA/STUDENT_PHOTO/') . $input['student_photo']; // path 2
    \File::copy($path1, $path2);

    $input['student_name'] = strtoupper ($request['student_name']);
    $input['student_father_name'] = strtoupper ($request['student_father_name']);
    $input['student_mother_name'] = strtoupper ($request['student_mother_name']);

    $id = $this->generateRegistrationId();
    $input['student_registration_id'] = $id;
    DB::table('locations')->insert([['center_code' => $id]])

    Student::create($input); 

   return back()->with('success',' STUDENT REGISTERD SUCCESSFULLY .');
}

function generateRegistrationId() {
    $id = 'SIIT_' . mt_rand(1000000000, 9999999999); // better than rand()

    // call the same function if the id exists already
    if ($this->registrationIdExists($id)) {
        return $this->generateRegistrationId();
    }

    // otherwise, it's valid and can be used
    return $id;
}

function registrationIdExists($id) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return Student::where('student_registration_id', $id)->exists();
}

答案 2 :(得分:0)

使用变量

set @num  = 0;

select
   ...
   @num := @num + 1 as row_number,