SQL 根据2列查询Select from 1 table and return data

SQL Query Select from 1 table and return data based on 2 columns

我正在处理 SQL 查询,其中我的数据存储在 table r. 中,基于 givereceive 的列,我需要将数据存储在临时 table 中,然后存储在新的 table 中。

本质上,数据是从 3 table 秒提取的,最终目标是获取图像的二进制代码并存储以在 .net

中显示

我现在正在想办法select

所以 give or receive in r 等于 Username in S, 如果 [=24] 显示所有相关数据并获取图像=] 等于 employee

我已经尝试了很多代码,我觉得 OR 可以解决问题,但似乎没有。

感谢您提供的任何帮助。

SELECT  
    r.id, r.give, r.[receive], r.[type], r.[description], r.isApproved, 
    r.photoGive, r.photoReceive 
INTO
    #temp2 
FROM 
    Intranet.dbo.Recgonize r

SELECT s.Employee, s.Username 
INTO #temp3 
FROM Vision7.dbo.SEUser s

SELECT p.Photo, p.Employee 
INTO #temp4 
FROM Vision7.dbo.EMPhoto p

SELECT * 
FROM #temp2 AS a
INNER JOIN #temp3 b ON a.give = b.Username 
INNER JOIN #temp4 c ON b.Employee = c.Employee

DROP TABLE #temp2
DROP TABLE #temp3
DROP TABLE #temp4

您可能想尝试以下操作:

-- Include only required columns select rather than "*"

SELECT * 
FROM #temp2 AS a
INNER JOIN #temp3 b ON a.give = b.Username 
INNER JOIN #temp3 b2 ON a.receive = b2.Username 
INNER JOIN #temp4 c ON b.Employee = c.Employee
INNER JOIN #temp4 c2 ON b2.Employee = c2.Employee

-- Include only required columns in select rather than "*"

SELECT * 
FROM 
        (select r.id, r.give as UserName, r.[type], r.[description], r.isApproved, r.photoGive  from #temp2
         union
         select r.id, r.[receive], r.[type], r.[description], r.isApproved, r.photoReceive from #temp2
        ) AS a
INNER JOIN #temp3 b ON a.UserName = b.Username 
INNER JOIN #temp4 c ON b.Employee = c.Employee

如果 temp tables 没有被应用程序用于必要的需要,相同的逻辑可以用于实际的 tables,只需将 #Temp2、#Temp3、#Temp4 替换为适当的 table 名字。

尝试使用如下单个脚本-

SELECT a.id, 
       a.give, 
       a.[receive], 
       a.[type], 
       a.[description], 
       a.isApproved, 
       a.photoGive, 
       a.photoReceive, 
       b.Employee, 
       b.Username, 
       c.Photo, 
       c.Employee
FROM Intranet.dbo.Recgonize A
     INNER JOIN Vision7.dbo.SEUser B ON a.give = b.Username
     INNER JOIN Vision7.dbo.EMPhoto C ON b.Employee = c.Employee;

为什么要为此使用临时表?这些只会让代码更难调试和维护,运行 的成本更高,理解起来也更复杂。

JOINs 将在没有临时表的情况下工作。但是您确实需要额外的逻辑才能在单独的列中获取给定值和接收值,因此需要更多 JOIN

SELECT r.id, r.give, r.[receive], r.[type], r.[description], 
       r.isApproved, r.photoGive, r.photoReceive,
       pg.Photo as give_photo, pg.Employee as give_employee,
       pr.Photo as receive_photo, pr.Employee as receive_employee
FROM Intranet.dbo.Recognize r LEFT JOIN
     Vision7.dbo.SEUser sg
     ON r.give = sg.Username LEFT JOIN
     Vision7.dbo.SEUser sr
     ON r.receive = sr.Username LEFT JOIN
     Vision7.dbo.EMPhoto pg
     ON sg.Employee = pg.Employee LEFT JOIN
     Vision7.dbo.EMPhoto pr
     ON sr.Employee = pr.Employee