sql查询多表查询问题

时间:2015-01-16 12:22:36

标签: php mysql sql

我在mysql db中有以下3个表。

项目表:

p_id    p_name     p_notes   is_active  p_owner     p_owner_id  p_date 
8       project    notes     1          shibbir     18          01-01-2015

Project_assign_clients:

pac_id  assign_clients  assign_client_id    is_main_user    p_id
39      Hara Adachi     8725                1               8
40      Aihara          8726                0               8
41      Akanuma Kenji   8023                0               8
42      Bayani Patrick  7801                0               8

Project_assign_users:

pas_id  assign_users    assign_user_id  p_id
5       teustace        12              8
6       alawson         10              8
7       mfischer        14              8
8      smitchell        15              8

现在我想了解用户创建的项目数量。例如我已经登录了id为18的用户,所以使用上面的表格应该使用mysqli_num_rows返回1个项目。这是我的查询,但它返回30奇怪!!

$logged_user_id = $_SESSION['user_id'];
$query = mysqli_query($link, "SELECT projects . *, projects_assign_clients . *, projects_assign_users . * FROM projects LEFT JOIN projects_assign_clients on projects.p_id = projects_assign_clients.p_id LEFT JOIN projects_assign_users ON projects.p_id = projects_assign_users.p_id WHERE projects.p_owner_id = '$logged_user_id' ");
$num =  mysqli_num_rows($query);
echo $num . " found"; // retrun 30 but should be 1 according to above table data

1 个答案:

答案 0 :(得分:0)

只需保留您的查询,还可以添加子选择以获取项目数量:

SELECT projects.*,
       projects_assign_clients.*,
       projects_assign_users.*,
       (select count(*) from projects where p_owner_id = p.p_owner_id)
FROM projects p LEFT JOIN projects_assign_clients
       ON projects.p_id = projects_assign_clients.p_id
  LEFT JOIN projects_assign_users ON projects.p_id = projects_assign_users.p_id
WHERE projects.p_owner_id = '$logged_user_id'