0

我想像这样使用 sql 内部连接到表:

$check_unscored =   "select * from [user]

            INNER JOIN [tenderrc]
            on [user].[id] = [tenderrc].[userid]";

$result_unscored = mssql_query($check_unscored, $s);

while ($record_unscored = mssql_fetch_array($result_unscored))
{
$id = $record_unscored['id'];
$name = $record_unscored['name'];   
$userid = $record_unscored['userid'];   
$touser = $record_unscored['touser'];

$id = $record_unscored['id'];
$username = $record_unscored['username'];   
$password = $record_unscored['password'];
}

我观察到两个表中都存在一个名为“id”的键名列,因此 $id = $record_unscored['id']; 将被覆盖;

我试过 $id = $record_unscored['user.id']; 但它不工作!实际上我该如何指定表名呢?

4

3 回答 3

1

使用别名:

$check_unscored =   "
       SELECT 
           u.id
         , u.name 
         , u.userid
         , u.touser
         , t.id          AS tender_id              --- column alias
                                                   --- to remove duplicate names
         , t.username 
         , t.password
        FROM [user]   AS u                         --- table alias her
            INNER JOIN [tenderrc]   AS t           --- and here
                ON  u.[id] = t.[userid]
                    ";
于 2012-04-27T09:22:40.003 回答
1

你可以创建一个别名字段等,如果你不想从用户中获取 ID,你可以使用类似这样的东西 select [user].[id] as 'userid', [tenderrc].[*] from ... 我来自 mySql 世界,但我认为它可以这样管理,然后以这种方式访问​​它 $id = $record_unscored['userid'];

于 2012-04-27T09:22:03.537 回答
0

您可以使用此功能执行此操作

http://hu2.php.net/manual/en/function.mssql-fetch-field.php

它可以提供“column_source - 从中​​获取列的表”。

示例代码:

$result = mssql_query("....");
$check_unscored = "
  SELECT *
  FROM       [user]
  INNER JOIN [tenderrc] ON [user].[id] = [tenderrc].[userid]";
$rows = fetch_multitable( mssql_query( $check_unscored, $s ));

foreach( $rows as $row ){
  echo $row->user['id'];
  echo $row->tenderrc['id'];
}

function fetch_multitable( $result ){
  $fields = mssql_num_fields( $result );
  $infos = array();
  for( $i=0; $i < $fields; $i++ ){
    $fieldinfo = mssql_fetch_field( $r, $i );
    $infos[ $i ] = (object)array(
      'table'=> $fieldinfo -> column_source
     ,'name' => $fieldinfo -> name
    );
  }

  $rows = array();
  while( $raw = mssql_fetch_row( $r )){
    $row = array();
    foreach( $raw as $i => $v ){
      $info = $infos[ $i ];
      $row[ $inf->table ][ $inf->name ] = $v;
    }
    $rows[] = (object)$row;
  }
  return $rows;
}
于 2012-04-27T09:20:50.253 回答