我想问一下有多个表的Mysql Select

时间:2014-10-14 12:21:40

标签: php mysql

我有一个表是session,并且有一个session_id,另一个表是namespmember1,namespmember2,namespmember3

每次我保存包含会话表的表单,namespmember1,namespmember2,namespmember3。他们都保存了。哪个ID是相同的,因为它们是批量保存的。

我的问题是。我想编辑那些表或查看...继承我的代码是多余的,我想有一个解决方案。

我获取会话表的ID。

$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT * FROM session WHERE session_id='$id'");
$row = mysql_fetch_object($q);

现在我将显示表名namespmember1,namespmember2,namespmember3

<?php
$sql = mysql_query("SELECT * FROM namespmember1 WHERE hon1_id='$id'");
while ($row = mysql_fetch_object($sql))
{
    echo "<tr>";
    echo "<td>$row->spmember_name</td>";
    echo "<td>$row->present</td>";
    echo "<td>$row->absent</td>";
    echo "<td>$row->leave_sick</td>";
    echo "<td>$row->business</td>";
    echo "</tr>";
}
$sql = mysql_query("SELECT * FROM namespmember2 WHERE hon2_id='$id'");
while ($row = mysql_fetch_object($sql))
{
    echo "<tr>";
    echo "<td>$row->spmember_name</td>";
    echo "<td>$row->present</td>";
    echo "<td>$row->absent</td>";
    echo "<td>$row->leave_sick</td>";
    echo "<td>$row->business</td>";
    echo "</tr>";
}
$sql = mysql_query("SELECT * FROM namespmember3 WHERE hon3_id='$id'");
while ($row = mysql_fetch_object($sql))
{
    echo "<tr>";
    echo "<td>$row->spmember_name</td>";
    echo "<td>$row->present</td>";
    echo "<td>$row->absent</td>";
    echo "<td>$row->leave_sick</td>";
    echo "<td>$row->business</td>";
    echo "</tr>";
}
?>

session_id等于不同表中的所有ID namespmember1,namespmember2,namespmember3

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用UNION,只需听取您的查询,所有子查询都应具有相同数量的列。

(SELECT spmbmbme_name, present, absent, leave_sick, business FROM namespmember1 WHERE hon1_id = '$id')
UNION
(SELECT spmbmbme_name, present, absent, leave_sick, business FROM namespmember2 WHERE hon2_id =  '$id')
UNION
(SELECT spmbmbme_name, present, absent, leave_sick, business FROM namespmember3 WHERE hon3_id = '$id')

答案 1 :(得分:0)

试试吧

 mysql_query("SELECT * FROM session s,namespmember1 n1,
    namespmember2 n2,namespmember3 n3 WHERE s.session_id='$id' and s.session_id=n1.hon1_id and n1.hon1_id=n2.hon2_id and n2.hon2_id=n3.hon3_id");