SQL连接两个表和重新标记列

时间:2013-11-03 00:20:55

标签: sql

我正在使用SQL数据库,这是一个DBMS。它是抒情数据库。 (我很乐意澄清我的描述是否不充分)。

我的销售人员表(包含salesid)如下:

销售人员

SalesID | FirstName | LastName
------- | --------- | --------
        |           |

和我的Studios表如下:

工作室:

StudioID | Name | City | Contact | SalesID
-------- | ---- | ---- | ------- | -------
         |      |      |         |

我已按以下方式启动查询:

select st.salesid, coalesce(sp.salesid, 'Does Not Work')
--Does This Match Harry Lee?
from studios st
inner join salespeople sp on sp.salesid = st.salesid;

以及:

select st.*
from studios st
inner join salespeople sp
    on sp.salesid = st.salesid
where st.contact = "Harry Lee";

但我不确定要重新标记该列。我知道要重新列出该列(因为我在上面的查询中使用了coalesce函数的提示)。

但是,如何在先前的查询中包含该内容,同时仍然坚持问题的细节?再次,如果我的描述不充分,我会很乐意澄清这个问题。

2 个答案:

答案 0 :(得分:1)

很难说出你想要的东西,但也许这样做:

select *
from SalesPeople s
where exists (
   select 1
   from   Studios
   where  Studios.SalesID = s.SalesID
      and Contact = 'Harry Lee'
   )

这是基于您问题的第二句中所述的要求,而不是您显示的代码示例(这有点令人困惑)。

编辑:阅读修改过的问题,试试这个:

select distinct a.SalesID
    . case when b.SalesID is null
           then 'doesn't work with Harry'
           else 'works with Harry'
           end as "Harry?"
from SalesPeople a
left outer join Studios b 
on   b.SalesID = a.SalesID
 and b.Contact = 'Harry Lee'

答案 1 :(得分:0)

coalesce(sp.salesid, 'Does Not Work With Harry Lee')将始终返回sp.salesid。原因是您正在使用INNER JOIN,根据定义,只有在匹配存在时才会返回一行。它不会返回空值。

您的陈述是正确的稍作修改:使用OUTER JOIN。您可以阅读更多相关信息以及here之间的差异。

尝试使用以下内容。这将返回Harry Lee作为联系人的所有可用销售人员以及所有未返回Does Not Work With Harry Lee的人员。

SELECT st.salesid, COALESCE(sp.salesid, 'Does Not Work With Harry Lee')
FROM studios st
LEFT JOIN salespeople sp ON sp.salesid = st.salesid;
WHERE st.contact = "Harry Lee";

如果您只对以Harry Lee联系的salesids感兴趣,请使用以下内容:

SELECT st.salesid
FROM studios st
INNER JOIN salespeople sp ON sp.salesid = st.salesid;
WHERE st.contact = "Harry Lee";

编辑:

在上次编辑之后,为了获得该结果,您应该使用以下内容。您可以使用WHERE子句控制查询结果:

SELECT st.salesid, 'works with Harry' AS [Harry?]
FROM studios st
INNER JOIN salespeople sp ON sp.salesid = st.salesid;
WHERE st.contact = "Harry Lee";

UNION ALL

SELECT st.salesid, 'doesn't work with Harry' AS [Harry?]
FROM studios st
INNER JOIN salespeople sp ON sp.salesid = st.salesid;
WHERE st.contact <> "Harry Lee";
相关问题