2012-09-10 39 views
2

這裏是我的SQL查詢SQL服務器:INNER JOIN寫出的東西兩次

select 
    tblUnderKategori.fldKategori, 
    tblUnderKategori.fldNavn, 
    tblUnderKategori.fldBillede, 
    tblKategori.fldId, 
    tblKategori.fldKategoriNavn 
from 
    tblUnderKategori 
inner join 
    tblKategori on tblUnderKategori.fldKategori=2  

正如你可以看到我所需要的一切在我的fldKategori = 2,而它確實是這樣,但它寫出來X2倍。

這裏是要顯示

katFac objKat = new katFac(); 
protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["id"])) 
    { 
     foreach (DataRow item in objKat.GetUnderkatByKat(Convert.ToInt32(Request.QueryString["id"])).Rows) 
     { 
      litUnderkategori.Text += item["fldNavn"].ToString() + "<br /><br />"; 
     } 
    } 
} 

對需要它的地方我的後端代碼我做不到SeeME所找出的問題,所以請人幫忙

預先感謝您! :)

+0

表結構.. – Learning

+0

我相信你有重複的行...檢查它首先 –

回答

2

由於您的連接缺少實際將兩個表連接在一起的條件,因此您在此處創建了一個Karthesian產品。
嘗試使用此:

select 
    tblUnderKategori.fldKategori, 
    tblUnderKategori.fldNavn, 
    tblUnderKategori.fldBillede, 
    tblKategori.fldId, 
    tblKategori.fldKategoriNavn 
from 
    tblUnderKategori 
     inner join tblKategori 
      on tblUnderKategori.fldKategori = tblKategori.fldId 
where tblUnderKategori.fldKategori=2 

這假定tblUnderKategori.fldKategori包含父類的ID。

+0

謝謝您的解答! :)謝謝你們,我終於修好了。謝謝! –

1

A JOIN連接兩個表,並且您必須提供公共列。如果您還想過濾掉某些值,請在之後添加WHERE子句。另外,如果您以後不明確地想要閱讀它們,則實際上並不需要SELECT用於匹配和連接的字段。

select 
    tblUnderKategori.fldNavn, 
    tblUnderKategori.fldBillede, 
    tblKategori.fldKategoriNavn 
from tblUnderKategori join tblKategori 
    on tblUnderKategori.fldKategori = tblKategori.fldId 
where 
    tblUnderKategori.fldKategori = 2  
1

ON子句指定應在哪個列上連接表,條件應包含在WHERE子句中。嘗試是這樣的:

SELECT 
    tblUnderKategori.fldKategori, 
    tblUnderKategori.fldNavn, 
    tblUnderKategori.fldBillede, 
    tblKategori.fldId,   
    tblKategori.fldKategoriNavn  
FROM tblUnderKategori   
    INNER JOIN tblKategori  
    ON tblUnderKategori.[some key column] = tblKategori.[corresponding key column]   
WHERE tblUnderKategori.fldKategori=2 
0

您的SQL語句中缺少一個字段來JOIN在桌子上。它應該是這樣的:

select u.fldKategori, 
    u.fldNavn, 
    u.fldBillede, 
    k.fldId, 
    k.fldKategoriNavn 
from tblUnderKategori u 
inner join tblKategori k 
    on u.fldKategori = k.fldId 
where u.fldKategori=2 

然後,您將在WHERE子句中應用您的過濾器。