[英]SQLite One-to-Many Relationship Set/Get Foreign Key
I am building an android app project with SQLite DB. 我正在用SQLite DB构建一个Android应用程序项目。
I got stuck on One-To-Many RelationShip. 我陷入了一对多关系之中。
This is One 这是一
private static final String createTableOrders =
"CREATE TABLE " + TABLE_ORDER + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
...
+ KEY_COLUMN_FORMATS + " INTEGER REFERENCES " + TABLE_FORMATS + "(" + KEY_ID + ")"
+ ");";
This is Many 这很多
private static final String createTableFormats =
"CREATE TABLE " + TABLE_FORMATS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
...
+ ");";
My problems is with set/get methods. 我的问题是使用set / get方法。 Lets say that I would need to get list of ids of all Formats that are in one Order. 让我们说我需要得到一个订单中所有格式的ID列表。 I guess same thing goes for set method. 我想set方法也是如此。
I tried to find this kind of question on SO but most of the question were just for SQL part. 我试图在SO上找到这样的问题,但大多数问题只是针对SQL部分。
PS Spent 3 hours trying to make it by myself but the only thing I got to was using GSON to code list of ids into String but it was just a dead-end. PS花了3个小时尝试自己做,但我唯一要做的就是使用GSON将ID列表编码成String但它只是一个死胡同。
EDIT: I need to get that information inside the code. 编辑:我需要在代码中获取该信息。
PSS I have been doing this for 18 hours so sorry if this is uber-stupid question. PSS我已经这样做了18个小时很抱歉,如果这是一个超级愚蠢的问题。
A one-to-many relationship requires the foreign key column in the "many" table: 一对多关系需要“many”表中的外键列:
CREATE TABLE Orders (
ID PRIMARY KEY
);
CREATE TABLE Formats (
ID PRIMARY KEY,
OrderID REFERENCES Orders(ID)
);
To get all formats belonging to an order, you just look up rows with the ID of that order: 要获取属于订单的所有格式,您只需查找具有该订单ID的行:
SELECT * FROM Formats WHERE OrderID = ?
In Jave: 在Jave:
Cursor cursor = db.query(TABLE_FORMATS,
new String[] { whatever columns you need },
"OrderID = " + orderID,
null, null, null, null, null);
while (cursor.moveToNext()) {
// read one order from the cursor
}
cursor.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.