开发者

How to construct SQL query

I am working to implement a data connec开发者_开发百科tion between my C# application and a SQL Server Express database. Please bear in mind I have not worked with SQL queries before.

I have the following relevant tables:

ArticlesCommon
ArticlesLocalized
CategoryCommon
CategoryLocalized

The ArticlesCommon table holds language independent information such as price, weight etc.

This is the statement for now:

SELECT * 
    FROM ArticlesCommon 
    INNER JOIN ArticlesLocalized ON ArticlesCommon.ID = ArticlesLocalized.ID 
WHERE ArticlesLocalized.Language = @language
ORDER BY ArticlesCommon.DateAdded

ArticlesCommon contains a category id for each row. Now, I want to use this to look up the localized information in CategoryLocalized and add it to the result, something like

SELECT *, CategoryLocalized.Name as CategoryName.

If I have gotten my point across, is this doable?

Edit:

Another question though. Both ArticlesLocalized and ArticlesCommon contain ID, which naturally are the same. I want to select everything from ArticlesCommon but everything except ID from ArticlesLocalized.. Is there a concise way to achieve this?

I guess that

SELECT * FROM .....

yield all columns from all joined tables?


what is the key that you need to JOIN ON

Does this work?

SELECT * FROM ArticlesCommon 
INNER JOIN ArticlesLocalized ON
ArticlesCommon.ID = ArticlesLocalized.ID 
INNER JOIN CategoryLocalized ON ArticlesCommon.ID = CategoryLocalized.ID
WHERE ArticlesLocalized.Language = @language
ORDER BY ArticlesCommon.DateAdded


Just add another Join

SELECT * FROM ArticlesCommon c 
   JOIN ArticlesLocalized L
       ON  a.ID = L.ID  
   JOIN CategoryLocalized CL
       ON  CL.ID = c.CategoryID  
WHERE ArticlesLocalized.Language = @language 
ORDER BY ArticlesCommon.DateAdded 

Use outer joins if not every row in ArticlesCommon has a CategoryId

SELECT * FROM ArticlesCommon c 
   JOIN ArticlesLocalized L
       ON  a.ID = L.ID  
   Left [OUTER] JOIN CategoryLocalized CL
       ON  CL.ID = c.CategoryID  
WHERE ArticlesLocalized.Language = @language 
ORDER BY ArticlesCommon.DateAdded 
  • [OUTER] is optional, as [Left] implies OUTER
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜