sql
  • jdbc
  • resultset
  • 2013-10-18 68 views 0 likes 
    0

    我有5個表,每個表中的模式是(com_no,uid,date)。我想訪問所有的表並獲取相同的uid的com_no。我在寫JDBC此查詢作爲訪問結果集中的多個表

    String s1= (String)session.getAttribute("uid"); 
    rs1=stat.executeQuery("select distinct com_no from hostel,sports where uid='"+s1+"'"); 
    while(rs1.next()) { 
    out.println(rs1.getString("com_no")); 
    } 
    

    但servlet異常是:

    The specified field 'com_no' could refer to more than one table listed in the FROM clause of your SQL statement. 
    

    任何人可以幫助我imrove此查詢或者給我一些其他的方式來做到這一點。任何幫助將不勝感激。

    +0

    這不是一個servlet異常,它是SQL異常。 SQL本身是不正確的。查詢數據庫時,必須正確指定列。如果com_no僅在其中一個表中可用,那麼它很好,否則會出錯。在沒有任何連接條件的情況下,在選擇查詢中指定兩個表需要什麼? –

    +0

    @AhhijithNagarajan我想打印所有在同一個uid多個表中的com_no。所以我試圖使用這個查詢。你能以其他方式建議嗎? – Ani

    +1

    你正在使用哪個數據庫?幾乎所有的數據庫,你都可以使用聯合, 從table1中選擇com_no,其中uid =? union 從table2中選擇com_no,其中uid =? –

    回答

    0

    請註明什麼是你需要通過檢索數據,但你可以嘗試下面的代碼,避免你現在得到了錯誤,

    rs1=stat.executeQuery("select distinct hostel.com_no as hostelcom, sports.com_no as sportscom from hostel join sports on hostel.uid=sports.uid where hostel.uid='"+s1+"'"); 
    
        while(rs1.next()) { 
        out.println(rs1.getString("hostelcom")); 
        } 
    

    你必須看看SQL連接查詢。

    0

    使用UNIONJOIN帶別名,以避免在SELECT查詢中不明顯的字段。

    首先,我想知道爲什麼你有5個表完全相同的計劃的原因?

    +0

    我有5個類別,都需要相同的屬性。 – Ani

    +0

    在這種情況下,請使用'JOIN'。什麼字段是你的表中的主鍵和外鍵? – kapand

    相關問題