显示两个表中的数据 - 从数据库中一次选择两个表

时间:2013-05-13 07:35:12

标签: mysql sql

如何一次选择两个不同的表?

第一张表(表名" table1")

capacity   comment

1.0        low
1.7        low  
7.2        average
9.9        fine
10.0       great

第二张表(表名"表2")

c1     c2     c3   c4

1.0     CC    AS   DD
1.7     AD    AC   PD
10.0    AW    AS   AD

如果输入为1.0,则应显示

capacity comment c2   c3   c4    
1.0       LOW    CC   AS   PD

更新

    select a.capacity,a.comment, b.c1,b.c2,b.c3 from table1 a inner join table2 b on a.capacity=b.capacity WHERE a.capacity= $name

  $rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error());


    $num = mysql_num_rows( $rs );

    if($num >= 1 ){
        echo "";
        while($row = mysql_fetch_array( $rs )){
    echo "<table>
        <tr>
            <th align='left' valign='middle'>Capacity</th>
            <td align='left' valign='middle'>$row[capacity]</td>
        </tr>
        <tr>
            <th align='left' valign='middle'>C2</th>
            <td align='left' valign='middle'>$row[c2]</td>
            </tr>               
        </table>";
     }

我预期的结果如(在前端)

| CAPACITY | 1.0|
|      C2  | CC |

但它显示出疑问

我预期的结果如(在前端)

| CAPACITY | 1.0|
|      C2  | CC |

| CAPACITY | 1.0|
|      C2  | CC |

2 个答案:

答案 0 :(得分:1)

尝试此查询

select a.capacity, a.comment, b.c2, b.c3, b.c4 from 
tbl1 a 
inner join 
tbl2 b
on a.capacity=b.c1
WHERE a.capacity=1

SQL FIDDLE

| CAPACITY | COMMENT | C1 | C2 | C3 | C4 |
------------------------------------------
|        1 |     low |  1 | CC | AS | DD |

答案 1 :(得分:1)

您只需要在sql中加入。

喜欢这个。

select a.*, b.C2, b.C3, b.C4 
from table1 a join table2 b
on a.capacity=b.c1
WHERE a.capacity=1.0

SQL code