mysqli在一个表中选择不同的2列,从两个表中选择不同的一列

时间:2016-08-15 12:10:59

标签: php mysql database mysqli

我有3张桌子

表用户

id db_fname db_lname

1    xxx    yyyy

2    zzz    zzzz

tbl_supplier

id db_companyname

1  xxxxxxxxx

tbl_subcontractor

id db_companyname

1   zzzzzzzzzz

2   zzzzzzzzzz

结果应为

xxx yyy
zzz zzz
zzzzzzz
xxxxxxx

fname和lname应该在一起

<?php
  $q=mysqli_query($conn,"SELECT db_fname as fname from tbl_user
   UNION 
  SELECT db_lname as lname from tbl_user
  UNION 
  SELECT db_CompanyName as scn from tbl_supplier 
  UNION 
  SELECT db_CompanyName as sucn from tbl_subcontractor

  ")or die(mysqli_error($conn));
  echo'<select name="txt_transferredto" class="form-control inpu-md">';

  while($row=mysqli_fetch_array($q)){
     $fname=$row['fname'];
     //$lname=$row['lname'];
     $companyname=$row['scn'];
     $subcompanyname=$row['sucn'];
     $name=$fname.' '.$lname;
  if($fname!=""){
   echo"<option value='$fname'>";echo $fname;echo"</option>";}
else if($subcompanyname!=""){      
    echo"<option value='$subcompanyname'>";echo $subcompanyname;echo"</option>";}
else if($companyname!=""){      
    echo"<option value='$companyname'>";echo $companyname;echo"</option>";}
  }

  echo'</select>';
  ?>

上面的代码给出了结果,但我不能一起打印 我有这个问题

( ! ) Notice: Undefined index: db_CompanyName in C:\wamp\www\order\projectmanagment\addactivities.php on line 147 Call Stack #TimeMemoryFunctionLocation 10.0026298808{main}(  )..\addactivities.php:0    ( ! ) Notice: Undefined index: db_CompanyName in C:\wamp\www\order\projectmanagment\addactivities.php on line 148 Call Stack #TimeMemoryFunctionLocation 10.0026298808{main}(  )..\addactivities.php:0    ( ! ) Notice: Undefined variable: lname in C:\wamp\www\order\projectmanagment\addactivities.php on line 149 Call Stack #TimeMemoryFunctionLocation 10.0026298808{main}(  )..\addactivities.php:0  

1 个答案:

答案 0 :(得分:0)

将concat用于第一个表

select 
    id, name, col1Code, col2Code, col2Value 
from 
    users_table UT
join 
    col1_table C1T on UT.id = C1T.user_ID_FK
join 
    col2_table C2T on UT.id = C2T.user_ID_FK
order by 
    UT.id 
limit 10