您好我有两张桌子:
1.teacher
id_t fname_t sname_t
1 john smith
2 john2 smith2
2.student
id_s id_t fname_s sname_s
1 1 sarah1 fox1
2 1 sarah2 fox2
3 2 sarah3 fox3
4 2 sarah4 fox4
5 1 sarah5 fox5
我想知道这个结果:
John Smith
sarah1 fox1
sarah2 fox2
sarah5 fox5
John2 Smith2
sarah3 fox3
sarah4 fox4
我可以通过这个对教师进行排序:
function getGroupsForMenu()
{
if($result = $this->db->query("SELECT * FROM teacher ORDER BY fname_t,lname_t ASC"))
{
$return = '';
while($r = $result->fetch_object())
{
fname_t=htmlspecialchars($r->fname_t);
lname_t=htmlspecialchars($r->lname_t);
$return .= fname_t." ".lname_t."<br/>";
}
print $return;
}
}
结果:
John Smith
John2 Smith2
我的问题:
如何加入2个表来获得此结果: 如何加入2个表来获得此结果:
John Smith
sarah1 fox1
sarah2 fox2
sarah5 fox5
John2 Smith2
sarah3 fox3
sarah4 fox4
答案 0 :(得分:1)
更改您的查询以使用INNER JOIN
SELECT t.fname_t, t.sname_t, s.fname_s, s.sname_s FROM teacher AS t
INNER JOIN student AS s ON t.id_t=s.id_t
ORDER BY t.fname_t, t.sname_t, s.fname_s, s.sname_s
这将使用教师ID加入两个表,并按返回的名称对结果进行排序。 您可以根据这些结果设置显示格式。
答案 1 :(得分:0)
查询
SELECT fname_t, sname_t, fname_s, sname_s
FROM teacher
JOIN student ON teacher.id_t = student.id_t
ORDER BY fname_t,lname_t, fname_s, sname_s
将为您提供如下结果集:
John Smith sarah1 fox1
John Smith sarah2 fox2
John Smith sarah5 fox5
John2 Smith2 sarah3 fox3
John2 Smith2 sarah4 fox4
要将其缩进格式,因为您的问题显示您需要适当的客户端php代码,以便在迭代结果集行时检测前两列中的更改。