簡體   English   中英

MySQL從表中選擇行,其中列鏈接到同一表中的另一列

[英]MySQL select rows from a table where column is linked to another column in same table

我有'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

有沒有解決方案?

以下代碼對您有所幫助,

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.所以這將返回三行。

它可以實現如下:

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;

我不確定我完全理解但看起來你的查詢中需要一個WHERE子句。

試試這個:

SELECT Emp_NO, Name, ReportingID
FROM Reslookup
WHERE ReportingID = <desired ID>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM