带有子查询的MySQL UPDATE为null

时间:2015-04-27 08:01:26

标签: mysql

我正在尝试使用子查询将所有飞机的状态更新为当前已退出且尚未返回的“OUT”。我的外键是PLANE_NUM。我正在尝试这样但我有一个错误:

 // bind the repo passed to the statement
  bind_buffers[0].buffer = &(backend->mysql->repo);
  bind_buffers[0].buffer_length = sizeof(backend->mysql->repo);
  bind_buffers[0].length = &bind_buffers[0].buffer_length;
  bind_buffers[0].buffer_type = MYSQL_TYPE_LONGLONG;

  // bind the oid passed to the statement
  bind_buffers[1].buffer = (void*)oid->id;
  bind_buffers[1].buffer_length = 20;
  bind_buffers[1].length = &bind_buffers[1].buffer_length;
  bind_buffers[1].buffer_type = MYSQL_TYPE_BLOB;

if (mysql_stmt_bind_param(backend->mysql->odb_read, bind_buffers) != 0)
      return GIT_ERROR;

  // execute the statement
  if (mysql_stmt_execute(backend->mysql->odb_read) != 0)
      return GIT_ERROR;

  if (mysql_stmt_num_rows(backend->mysql->odb_read) == 1) {
    result_buffers[0].buffer_type = MYSQL_TYPE_TINY;
    result_buffers[0].buffer = type_p;
    result_buffers[0].buffer_length = sizeof(type_p); //sizeof(signed char);
    result_buffers[0].is_null = 0;
    result_buffers[0].length = &type_len;
    memset(type_p, 0, sizeof(type_p));

    result_buffers[1].buffer_type = MYSQL_TYPE_LONGLONG;
    result_buffers[1].buffer = len_p;
    result_buffers[1].buffer_length = sizeof(len_p);
    result_buffers[1].is_null = 0;
    result_buffers[1].length = &len_len;
    memset(len_p, 0, sizeof(len_p));

    result_buffers[2].buffer_type = MYSQL_TYPE_LONG_BLOB;
    result_buffers[2].buffer = 0;
    result_buffers[2].is_null = 0;
    result_buffers[2].buffer_length = 0;
    result_buffers[2].length = &data_len;

    if (mysql_stmt_bind_result(backend->mysql->odb_read, result_buffers) != 0)
      return GIT_ERROR;

error = mysql_stmt_fetch(backend->mysql->odb_read);

3 个答案:

答案 0 :(得分:2)

更好的方法是加入

update plane p
left join flight f
on p.PLANE_NUM = f.PLANE_NUM
SET p.STATUS='OUT'
where f.FLIGHT_RETURNDATE IS null ;

答案 1 :(得分:1)

你面临的问题是因为==> MySQL不允许引用一个在FROM子句中以更新为目标的表,这可能令人沮丧。

这对你有用

UPDATE plane
SET STATUS='OUT'
WHERE PLANE_NUM 
IN (SELECT * FROM (select p.PLANE_NUM
    FROM plane p, flight f
    WHERE p.PLANE_NUM = f.PLANE_NUM
    AND FLIGHT_RETURNDATE IS null) as B );

未优化。请参阅以下链接并根据您的要求进行优化

You can't specify target table for update in FROM clause

http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

答案 2 :(得分:0)

试试这个。

UPDATE airplane, plane, flight
SET airplane.STATUS='OUT'
WHERE airplane.PLANE_NUM = plane.PLANE_NUM
    AND plane.PLANE_NUM = flight.PLANE_NUM
    AND flight.LIGHT_RETURNDATE IS null