MySQL从表中选择行,其中列链接到同一表中的另一列

时间:2018-02-22 09:59:00

标签: mysql sql

我有'Reslookup'表,其中,我想选择向另一个ReportingID报告的员工。

以下是我的表格的简化版本,内容为:

Emp_NO   Name    ReportingID
531       A         16
1572      B         531
1032      C         1572
and so..on..

Now, If I select ReportingID = 16 (in where condition), then Employees 531,1572,1032 should fetch,

Similarly, If I select ReportingID = 531 (in where condition), then Employees 1572,1032 should fetch,

Similarly, If I select ReportingID = 1572 (in where condition), then Employees 1032 should fetch

有没有解决方案?

3 个答案:

答案 0 :(得分:4)

以下代码对您有所帮助,

select Emp_No, Name, ReportingID
from Reslookup as t1
where ReportingID = 16
      or exists 
       (   select * 
           from Reslookup as t2
           where Emp_No = t1.ReportingID 
           and 
             (
                ReportingID = 16 
                or exists 
                 ( 
                    select * 
                    from Reslookup as t3
                    where Emp_No = t2.ReportingID 
                    and ReportingID = 16
                 )                 
              ) 
        ) 

你必须通过ReportingID,这里我把它作为16.所以这将返回三行。

答案 1 :(得分:1)

可以通过以下方式实现:

SELECT GROUP_CONCAT(rid SEPARATOR ',') FROM (
SELECT @rid:=(SELECT GROUP_CONCAT(Emp_NO SEPARATOR ',') FROM EMP 
             WHERE ReportingID IN (@rid)) AS rid FROM EMP
JOIN
(SELECT @rid:=16)tmp
WHERE ReportingID IN (@rid)) a;

演示链接:http://sqlfiddle.com/#!9/5be043/1

表格架构和数据:

CREATE TABLE EMP
(
    `Emp_NO` INT(11) DEFAULT NULL,
  `Name` VARCHAR(20) DEFAULT NULL,
  `ReportingID` INT(11) DEFAULT NULL
);

INSERT INTO `EMP` VALUES(531,'A',16);
INSERT INTO `EMP` VALUES(1572,'B',531);
INSERT INTO `EMP` VALUES(1032,'C',1572);

以tabualr格式获取数据:

SELECT * FROM (
SELECT @rid:=(SELECT GROUP_CONCAT(Emp_NO SEPARATOR ',') FROM EMP 
         WHERE ReportingID IN (@rid)) AS rid, NAME FROM EMP
JOIN
(SELECT @rid:=16)tmp
WHERE ReportingID IN (@rid)) a;

答案 2 :(得分:0)

我不确定我是否完全理解,但您的查询中似乎需要<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="10" android:padding="5dp"> <TextView android:layout_weight="7" android:layout_width="0dp" android:text="some text" android:layout_height="wrap_content"/> <Button android:text="btn1" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content"/> <Button android:text="btn2" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content"/> <Button android:text="btn3" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content"/> </RelativeLayout> 子句。

试试这个:

WHERE