将SQL语句合并为一个

时间:2018-01-09 09:42:08

标签: sql

我的任务是读取两个表的数据,这些表需要几个SQL语句,只有一个查询。

我知道这是可能的,我已经就此事做了一些研究,但遗憾的是这对我没有帮助,因为我不知道如何将这个应用到我的问题中。

我认为这不是太复杂,但由于我缺乏SQL经验,这对我来说是一个很大的挑战。

出于理解目的,我想知道如何将这三个陈述合并为一个。

我有两张桌子。 " PEmpl"和"部门"我有值ID。

PEmpl有列:" DepartmentID"和" PEmplID"

部门有专栏:" DepartmentID" " DepartmentName的"和#34; FatherDepID"

我有EmployerID,想知道他有哪些部门的权限,所以我想出了这三个陈述。 (我已经使用这些查询编程了它在C#中工作,但遗憾的是,任务是仅在1个查询中执行它而没有c#)*

SELECT DepartmentID
FROM PEmpl
WHERE PEmplID = @ID <-- the  ID i have

SELECT DepartmentName
FROM Department
WHERE DepartmentID = @DepartmentID <- The DepID i got from the last query

SELECT DepartmentName
FROM Department
WHERE FatherDepID = @DepartmentID <- same ID as last querys

但我不知道如何将这些结合起来1.我希望有人可以给我一些线索。我不希望得到完整的答案,但是对正确方向的推动将不胜感激。

这是我用C#编程的。我有这个人及其身份证,你看到他已经获得了#34; Musterfirma Gmbh&#34;因为这是其他人的父亲部门,所以他也允许这些人。

enter image description here

PS:我希望我解释它是可以理解的。如果不让我知道,我会尝试改写它:)

5 个答案:

答案 0 :(得分:1)

我不确定我是否正确理解了您的问题(请发布一些示例数据)。我想你可以尝试下面的查询。 我只使用一个OR条件的连接,并添加一列来识别父亲,直接或两个deps。 我使用了表的“别名”(A代表PEmpl,B代表部门简化阅读查询)

SELECT B.DepartmentName
      , CASE WHEN A.DepartmentID=B.DepartmentID AND A.DepartmentID=B.FatherDepID THEN 'B' /* both */
             WHEN A.DepartmentID=B.DepartmentID THEN 'D' /* "direct" dep */
             ELSE 'F'  /* father */                              
        END AS GR  /* case updated thanks to Caleth suggestion */
FROM  PEmpl A
INNER JOIN Department B ON A.DepartmentID=B.DepartmentID OR A.DepartmentID=B.FatherDepID
WHERE A.PEmplID = @ID 

如果您只需要没有(可能)“重复”部门的记录,您可以删除GR列并在SELECT之后使用DISTINCT。

答案 1 :(得分:0)

像这样可能

SELECT 
DepartmentID as dep0
FROM PEmpl 
    LEFT JOIN Department as dep1 on (dep0.DepartmentID = dep1.DepartmentID)
    LEFT JOIN Department as dep2 on (dep0.DepartmentID = dep2.DepartmentID)
WHERE PEmplID = @ID

答案 2 :(得分:0)

你可能正在寻找这个

struct A

答案 3 :(得分:0)

尝试一下,如果它不起作用,请修复加入列,然后查看joins您需要的内容

  SELECT d2.DepartmentId, d2.DepartmentName 
  FROM PEmpl e
       JOIN Department d1 on e.DepartmentID = d1.DepartmentID
       JOIN Department d2 on d2.FatherDepID = d1.DepartmentID
  WHERE e.PEmplID = @ID   <-- your ID

答案 4 :(得分:0)

您需要JOIN,或者可能需要很多。

WITH Deps AS (
-- This finds the parent departments. We have two copies of the same DepartmentID to have the same shape results as below
    SELECT DepartmentName, DepartmentID AS Link, DepartmentID
        FROM Departments 
-- Combine results from two SELECT clauses (without duplicates)
    UNION
-- This will find all the child departments, all the child's children, etc
    SELECT child.DepartmentName, child.DepartmentID AS Link, parent.DepartmentId
        FROM Departments AS child
-- We can join on the results we are selecting, to follow links
        JOIN Deps AS parent ON child.FatherDepID = parent.Link )
SELECT DepartmentName
-- To add any other columns from Departments, be sure to include them in both SELECT clauses above
    FROM PEmpl
    JOIN Deps ON PEmpl.DepartmentID = Deps.DepartmentID