我希望使用不同的ID(CustomerID
,OrderID
)连接到数据库中的表。我使用以下代码创建我的外键:
FOREIGN KEY("+ COLUMN_ORDER_ID + ") REFERENCES+TABLE_NAME_CUSTOMER + "(" + COLUMN_CUSTOMER_ID + "));";
我没有发布完整的源代码,因为我的第一个表工作正常,我认为问题是外键。
我用这种方法过滤我的数据:
public List<Orders> getOrdersByCustomerID() {
List<Orders> orderList = new ArrayList<Orders>();
String query = "select " + COLUMN_ORDER_ID
+ "," + COLUMN_ORDER_NAME
+ "," + COLUMN_SETS
+ "," + COLUMN_REPEATS
+ "," + COLUMN_SECTION
+ " from " + TABLE_NAME_ORDERS
+ " where " + COLUMN_CUSTOMER_ID
+ "=" + COLUMN_ORDER_ID;
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Orders orders = new Orders(cursor.getString(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getString(4));
orderList.add(orders);
} while (cursor.moveToNext());
}
db.close();
return orderList;
}
我收到此错误消息:
06-26 17:11:26.154 10163-10163 / com.xxx.xxx.xxx
E / AndroidRuntime:FATAL EXCEPTION:主进程:com.xxx.xxx.xxx,PID:10163
java.lang.RuntimeException:无法启动活动 android.database.sqlite.SQLiteException:没有这样的列: customerId(Sqlite代码1):,编译时:选择 orderId,orderName,sets,repeats,order from section where customerId = orderId,(操作系统错误 - 2:没有这样的文件或目录)
我认为这两个ID之间的连接不正确,还是我必须从客户表中提交id?有小费吗?根据我的理解,Customer
可以有多个Order
。这就是我使用外键的原因;我希望这是正确的。
答案 0 :(得分:0)
编辑:我错了,显然查询在mysql默认情况下不区分大小写。
编辑: 为了创建外键,两个表都必须包含ConsumerId。这允许您使用外键建立关系。 创建外键后,您的查询也必须更改。它应该是这样的
select " + COLUMN_ORDER_IDq
+ "," + COLUMN_ORDER_NAME
+ "," + COLUMN_SETS
+ "," + COLUMN_REPEATS
+ "," + COLUMN_SECTION
+ " from " + TABLE_NAME_ORDERS + "," + TABLE_NAME_CUSTOMERS
+ " where " + TABLE_NAME_ORDERS +"." + COLUMN_CUSTOMER_ID
+ "=" + TABLE_NAME_CUSTOMERS + "." + COLUMN_CUSTOMER_ID