我有两张表
+----------------------------+
| task |
+----------------------------+
| id | t_title | t_assign_to |
+----------------------------+
+-----------------------------+
| task_employee |
+-----------------------------+
| id | emp_name | emp_underon |
+-----------------------------+
我的问题是我想要获取t_assign_to FROM任务表,其中有emp_underon =' 2'在具有外键(t_assign_to)的task_employee表中
<?php
$sql = mysql_query("SELECT * FROM task");/// i got all value from here
$sql=mysql_query("SELECT * FROM task_employee WHERE emp_underon ='2'");// i got all value from here
//$sql=mysql_query("SELECT * FROM task UNION SELECT * FROM task_employee WHERE emp_underon='2'");
$count = mysql_num_rows($sql);
while($row=mysql_fetch_assoc($sql))
{
echo $row['t_assign_to'];
}
?>
答案 0 :(得分:0)
我认为t_assign_to是task_employee的外键 所以我一起加入他们
架构1
$sql = "SELECT * FROM task t INNER JOIN task_employee te ON t.t_assign_to = te.id";
架构2
$sql = "SELECT * FROM task t,task_employee te WHERE t.t_assign_to = te.id";
如果表中的字段名称与其他表中的其他字段相同,只需更改字段名称,如:
$sql = "SELECT table.field as new_field_name FROM task t,task_employee te WHERE t.t_assign_to = te.id";
为方便起见,
$sql = "SELECT * FROM task t INNER JOIN task_employee te ON t.t_assign_to = te.id WHERE te.emp_underon = '2' "
$q = mysql_query($sql);
$c = mysql_num_rows($q);
if($c > 0)
{
while($r = mysql_fetch_assoc($q))
{
echo $r['t_assign_to'];
}
}
答案 1 :(得分:0)
我希望你能通过这个查询得到你的答案,虽然我没有测试这个SQL。
select task.t_title, task.t_assign_to, task_employee.id as emp_id, task_employee.emp_name from task inner join task_employee on task.t_assign_to = task_employee.emp_underon where task_employee.emp_underon = 2