我有两个表表联系人和表公司。 在表格联系中有4列称为公司ID(1-4) 在这些列中,存在与该人员相关联的公司ID。 现在的问题是,我希望能够显示公司名称而不是id,我尝试使用以下查询,但它只给出了我最后一行的值
select *
from contact as ct
join company as cy1 on cy1.Company_id = ct.Company_id1
join company as cy2 on cy2.Company_id = ct.Company_id2
join company as cy3 on cy3.Company_id = ct.Company_id2
join company as cy4 on cy4.Company_id = ct.Company_id4
$stmt = sqlsrv_query( $conn, $sql , array(), array( "Scrollable" => 'static' ) );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$stmtcount = sqlsrv_num_rows($stmt);
if ($stmtcount > 0) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$id = $row['Contact_id'];
$fname = $row['Firstname'];
$lname = $row['Lastname'];
$company1=$row['Company'];
$company2=$row['Company'];
$company3=$row['Company'];
$company4=$row['Company'];
echo '<tr>';
echo "<td> <a class='notice' href='details.php?id=" . $id . " '>" .$row['Abbreviation'].' '. $row['Firstname'] . "</a> </td>";
echo '<td>'.$lname.'</td>';
echo '<td>'.$company1.'</td>';
echo '<td>'.$company2.'</td>';
echo '<td>'.$company3.'</td>';
echo '<td>'.$company4.'</td>';
echo '</tr>';
结果如下result of the query 表结构
答案 0 :(得分:0)
尝试使用列别名而不是select *
:
select ct.*,
cy1.name as name1,
cy2.name as name2,
cy3.name as name3,
cy4.name as name4
from contact ct join
company cy1
on cy1.Company_id = ct.Company_id1 join
company
cy2
on cy2.Company_id = ct.Company_id2 join
company cy3
on cy3.Company_id = ct.Company_id2 join
company cy4
on cy4.Company_id = ct.Company_id4;
如果多个列具有相同的名称,则查询将任意选择一个值。