dpntq48842 2015-11-21 08:30
浏览 104
已采纳

php mysql使用pdo在同一个表上连接查询

This is my table in which ID is table's primary key and SUPER_ID is used to manage hierarchy for example here, A is super user of B and B is super user of C while A is super-super user of C............ ID AND SUPER_ID MAY NOT NECESSARY BE SEQUENTIAL

Now question is when A is logged in, He can see details of his own and of Both B and C While B is logged in He can see details of His own and C only. And C can see his own details only.

I have written this query:

<?php
$sql="SELECT * from TABLE 
WHERE 
ID =:loginId OR                                                  
ID IN 
(
SELECT ID FROM TABLE 
WHERE SUPER_ID =:SuperId
)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':logedIn' => $_SESSION['sess_login_id'] , ':SuperId' => $_SESSION['sess_login_id']) );
?>

This query gives me results of A and B when i logged in as User A. What query should I write so that I can get results of A , B and C when I logged in as User A? Because A is a super user of B and super-super user of C. Please help. Thank You.

  • 写回答

2条回答 默认 最新

  • donglin4636 2015-11-21 11:44
    关注

    If you have only three hierarchy levels, you can do it like this:

    SELECT DISTINCT u.*
    FROM user loggedin
    LEFT JOIN user children      ON children.SUPR_ID      = loggedin.ID
    LEFT JOIN user grandchildren ON grandchildren.SUPR_ID = children.ID
    JOIN user u ON u.ID IN (loggedin.ID, children.ID, grandchildren.ID)
    WHERE loggedin.ID = :loginId
    

    http://sqlfiddle.com/#!9/3d93c/7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制