如何使用mysql使用mysql从两个表中获取列数据

时间:2015-04-13 11:11:31

标签: php mysql

我有两个表ownership_profilesocity_unit

查询表1: select * from ownership_profile where SID='$id'

查询表2: select * from socity_unit where socity_id='$sid'

我必须加入一个查询,但我不知道该怎么做。

这是我的Php代码,但却出错:

<!-----------------Table For User Names-------------------------------------->      
<table border="1"  align="center">
        <tr>
            <th>Unit No</th>
            <th>Member Name</th>
            <th>Wing</th>
            <th>Unit</th>
        </tr>
    <?php
    if(isset($_GET['submit']))
    {
    $sql = "select * from ownership_profile o inner join society_unit s on o.sid = s.society_id where o.sid = '$sid' ";
    $result = mysql_query($sql);
    $i=1;
    while($row=mysql_fetch_array($result)){
    ?>



        <?php
    $name = $row['NAME'];
    $unitid = $row['UNIT_ID'];
    $sid = $row['SID'];
    $wings = $row['wings'];
    $unit_no = $row['unit_no'];
    {
    ?>  

    <!--User Submit Result-->
        <tr>
            <td><?php echo $unitid; ?></td> 
            <td><?php echo $name; ?></td>   
            <td><?php echo $wings; ?></td>  
            <td><?php echo $unit_no; ?></td>
            </tr>
        <?php }?>
    <?php
    //echo "<br>";
    $i++;
    }
    }
    ?>

3 个答案:

答案 0 :(得分:0)

inner join就是你想要的。

select *
  from ownership_profile o
    inner join society_unit s
      on o.sid = s.society_id
  where o.sid = '$sid'

这假定'sid'和'society_id'是关系标识符。

答案 1 :(得分:0)

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

答案 2 :(得分:0)

select * from ownership_profile o inner join socity_unit s on o.SID = s.socity_id where o.SID = '$SOCIETY_ID'

此查询工作正常,但......它从表中生成dublicate条目