如何使用连接查询从两个以上的表中获取数据,而无需外键和主键

时间:2012-08-24 06:21:27

标签: asp.net sql-server ado.net

一旦我需要你的帮助,

我的数据库中有三个表。

1>的婚礼

Column Name    Data Type
-------------------------------------
wedID          Int (primary key)
wedName        varchar (50)

2 - ;的 selectSite

Column Name   Data Type
-----------------------------------
wedID         Int (without foreign key and primary key with null allow)
siteID        Int (without foreign key and primary key with null allow)
siteStatus    varchar(50)

3> 网站

Column Name   Data Type
--------------------------------      
siteID        Int (Primary Key) 
siteName      varchar(50)
siteFile      varchar(MAX)

我想要以下输出:

 ws.siteID     ws.siteName     ws.siteFile    s.wedID   s.sitestatus
 ----------------------------------------------------------------------------
 1              Show           show.jpeg      6         Yes
 2              My View        my view.png    5     
 3              Dream          dream.jpeg     3     

wswebSite表的别名,ssiteSelect表的别名。

来自webSite表的所有数据以及来自siteSelect的数据s.siteStatus如果wedID不匹配则Yes不显示

我尝试按照sql查询

select 
    DISTINCT(ws.siteID), s.wedID, ws.siteName, 
    ws.siteFile, s.siteStatus 
from wedding wd, webSite ws 
left outer join siteSelect s on ws.siteID = s.siteID 
where wd.wedID = @wedID

但是输出是这样的:

 ws.siteID     ws.siteName     ws.siteFile    s.wedID   s.sitestatus
 -----------------------------------------------------------------------
 1              Show           show.jpeg      6         Yes
 2              My View        my view.png    5         Yes
 3              Dream          dream.jpeg     3         Yes

2 个答案:

答案 0 :(得分:2)

<强> DEMO SQL FIDDLE

检查演示添加一些值并运行此查询

select 
   ws.siteId, ws.siteName, ws.siteFile, ss.wedID,
   (case 
      when ss.wedID = 1 then ss.siteStatus else '' end) as siteStatus
from 
   website ws 
join 
   selectsite ss on ss.siteID=ws.siteID

让我知道是否有任何疑问

答案 1 :(得分:0)

试试这个

select 
    DISTINCT(ws.siteID), s.wedID, ws.siteName, ws.siteFile, 
    (case 
        when s.wedID = @wedID 
        then s.siteStatus 
        else '' end) as siteStatus, wd.wedName
from webSite ws  
left join selectSite s on ws.siteID = s.siteID  
Left Join wedding wd on wd.wedID = s.wedID