没有得到sqlite查询的结果

时间:2014-02-18 10:36:23

标签: android sql database sqlite

我在 sqlite 数据库上运行以下查询。我知道至少有contact表中的条目,但我没有得到任何结果。

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"
      + ");";

2 个答案:

答案 0 :(得分: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

希望这会对你有所帮助。

答案 1 :(得分: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