2014-02-18 117 views
-1

我對的SQLite數據庫運行下面的查詢。我知道至少在contact表中有條目,儘管我沒有得到任何結果。沒有得到結果的SQLite查詢

SELECT * 
    FROM contact, 
     phone, 
     email 
WHERE cnt_cnt_id = phn_cnt_id 
     AND phn_cnt_id = eml_cnt_id 
     AND cnt_cnt_id = 1111 

形成我的查詢可以得到我想要加入這三個表的想法。 我應該怎麼做才能從所有三個表中檢索id爲1111的數據?

EDIT(表模式):

private static final String CONTACT_TABLE = "create table " 
    + TABLE_NAME_CONTACT + "(" 
    + COLUMN_ID     + " integer primary key autoincrement, " 
    + COLUMN_CNT_CONTACT_ID   + " text not null, " 
    + COLUMN_CNT_FIRST_NAME   + " text not null," 
    + COLUMN_CNT_LAST_NAME   + " text not null," 
    + COLUMN_CNT_NICK_NAME   + " text not null"  
    + ");"; 

    private static final String PHONE_TABLE = "create table " 
     + TABLE_NAME_PHONE + "(" 
     + COLUMN_ID     + " integer primary key autoincrement, " 
     + COLUMN_PHN_CONTACT_ID   + " text not null, " 
     + COLUMN_PHN_NUMBER   + " text not null" 
     + ");"; 

    private static final String EMAIL_TABLE = "create table " 
     + TABLE_NAME_EMAIL + "(" 
     + COLUMN_ID     + " integer primary key autoincrement, " 
     + COLUMN_EML_CONTACT_ID   + " text not null, " 
     + COLUMN_EML_EMAIL_ID    + " text not null" 
     + ");"; 
+0

添加表的模式。 – astuter

+0

這3個表中存在什麼值? – Mathew

+0

@Mathew:用戶名稱暗示的細節。 – astuter

回答

0

我解決它以這樣的方式

SELECT * FROM 
contact LEFT JOIN phone ON cnt_cnt_id = phn_cnt_id        
      LEFT JOIN email ON phn_cnt_id = eml_cnt_id         
      WHERE cnt_cnt_id = 1111 
1

第一件事是,你還沒有使用外鍵這是強制性的加入兩個表和檢索數據。 Look here>外鍵如何工作。

您必須添加CONTACT_ID作爲

Syntax :FOREIGN KEY(Child tbl id name) REFERENCES TABLE_NAME_CONTACT(Parent tbl id name) 

FOREIGN KEY(COLUMN_PHN_CONTACT_ID) REFERENCES TABLE_NAME_CONTACT(COLUMN_CNT_CONTACT_ID) 
FOREIGN KEY(COLUMN_EML_CONTACT_ID) REFERENCES TABLE_NAME_CONTACT(COLUMN_CNT_CONTACT_ID) 

表模式:

CREATE TABLE "CONTACT" (
    "cnt_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    "fname" TEXT NOT NULL, 
    "lname" TEXT NOT NULL, 
    "nickname" TEXT NOT NULL 
) 

CREATE TABLE "PHONE" (
    "ph_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    "ph_number" INTEGER NOT NULL, 
    "cnt_id" FOREIGN KEY(cnt_id) REFERENCES TABLE_NAME_CONTACT(cnt_id) 
) 

CREATE TABLE "EMAIL" (
    "email_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    "email_address" INTEGER NOT NULL, 
    "cnt_id" INTEGER NOT NULL, FOREIGN KEY(cnt_id) REFERENCES TABLE_NAME_CONTACT(cnt_id) 
) 

調整你的表名&領域和更多的參考檢查here

希望這會幫助你。