我有3张桌子:
Table.Keys,Table.Tags,Table.Values
Table.Keys create table statement:
createTableStatement = "CREATE TABLE " + Tables.KEYS + "("
+ KeysColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KeysColumns.KEY + " TEXT NOT NULL,"
+ "UNIQUE ("
+ KeysColumns.KEY
+ ") ON CONFLICT IGNORE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
Table.Tags create table statement:
createTableStatement = "CREATE TABLE " + Tables.TAGS + " ("
+ TagsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TagsColumns.NAME + " TEXT NOT NULL,"
+ "UNIQUE ("
+ TagsColumns.NAME
+ ") ON CONFLICT IGNORE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
Table.Value create table statement:
createTableStatement = "CREATE TABLE " + Tables.VALUES + " ("
+ ValuesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ValuesColumns.KEY_ID + " TEXT NOT NULL,"
+ ValuesColumns.TAG_ID + " TEXT NOT NULL,"
+ ValuesColumns.VALUE + " TEXT NOT NULL,"
+ "UNIQUE ("
+ ValuesColumns.KEY_ID + ", " + ValuesColumns.TAG_ID
+ ") ON CONFLICT REPLACE"
+ ");";
execSQL(sqLiteDatabase, createTableStatement);
如果我进行以下加入:
Tables.KEYS
+ " JOIN " + Tables.VALUES
+ " ON " + Values.KEY_ID + " = " + Keys.column(Keys._ID)
+ " JOIN " + Tables.TAGS
+ " ON " + Values.TAG_ID + " = " + Tags.column(Tags._ID);
我当然得到重复的行,因为结果是
KEY | TAG | VALUE
=================
| |
我想要完成的是从表或视图中查询并获取一个Cursor,没有重复的行,具有以下模式:
KEY | TAG 1 | TAG 2 | ... | TAG n
=================================
| | | |
并非所有键必须都有每个标签的值,但所有 CAN 键都有值。
我不知道如何做到这一点。我甚至不确定从哪里开始。
与此同时,我创建了另一个表,它存储了一些我知道将永远存在的TAG值。
但是我觉得这是低效的,因为在任何时候我都可以拥有'n'个新的TAG值,这就是为什么我希望能够创建一个包含我列出的模式的视图或表。
答案 0 :(得分:1)
SQLite没有透视功能;你必须分两步完成这个任务。
首先,获取所有可能的标签:
SELECT _id, Name
FROM Tags
ORDER BY Name;
然后,使用返回的数据构建一个查询,查找每个键的每个可能标记:
SELECT Key,
(SELECT Value
FROM Values
WHERE Key_ID = Keys._id
AND Tag_ID = 111
) AS Tag_111,
(SELECT Value
FROM Values
WHERE Key_ID = Keys._id
AND Tag_ID = 222
) AS Tag_222,
...
FROM Keys;