2

我需要一个查询来选择一堆条目,然后用这些条目将一堆行选择成一行。下面显示了一个典型的条目,以及一个典型的结果需要看起来像什么。

table1
id
-------
3     

table2
id      value       table1
--------------------------
5       value1      3
6       value2      3

table3
id      value       table1
-------------------------
9       value3      3
10      value4      3

table4
id      table1
---------------
14      3
15      3

table5
id      value       table4
-------------------------------
19      value5      14
20      value6      14
21      value7      15


result
result1 result2     result3     result4
------------------------------------------------------
3       value1      value3      value5, value6; value7

只需要表 1 和表 2 的第一个结果。表 2 通常可以为 null,value3 需要进入 result2。目前,我使用如下语句选择每个条目,该语句仅返回 result1,然后对于每个条目,我对每个结果进行单独查询

SELECT DISTINCT id FROM (
    -complicated select in here
) AS temp;

然后对于每个 id 分别执行:

SELECT value FROM table2 WHERE table1 = id LIMIT 1;

SELECT value FROM table3 WHERE table1 = id LIMIT 1;

SELECT value, table4.id FROM table4, table5 WHERE table4.id = table5.table4 AND table1 = id;

并使用代码将其格式化为结果表之类的东西。

问题是只有第一个查询是在后台线程上完成的,而其余的都是在 UI 线程上完成的。我想在一个查询中完成所有操作,但是在将 table4 放入单行并且只选择 table2 和 table3 的第一个结果时遇到了麻烦。

4

1 回答 1

3

For conditional relationships like this you will have a much easier time running multiple selections, or creating a temporary table, filling it with keys in stages and then doing a final selection against the temporary table.

Looking at result4, in effect you are attempting to denormalise and then renormalise the data in the table using outer joins with conditional logic, it is probably possible to do, but would run against the grain of 'wise' database development and you are likely to end up with a query that is all but impossible to debug if you run into problems.

I know that sqlite is meant to be a simple implementation of the SQL standard for using in lightweight environments, so I'm not sure how complex your SQL can be before it gets into trouble.

It's not entirely clear to me what you are trying to achieve, but a workaround might be using several UNION statements like this:

SELECT DISTINCT source, id FROM (
    SELECT table2.table1 AS table1, 'table2' AS source, value AS id FROM table2 
    UNION
    SELECT table3.table1, 'table3', value FROM table3 
    UNION
    SELECT table4.table1, 'table5', value FROM table5, table4 
    WHERE table4.id = table5.table4)
WHERE table1 = 3;

Then you would get result like this:

source    | id
-----------------------
table2    | value1
table3    | value3
table4    | value5
table4    | value6
table4    | value7

Your other option is to create a view with all the unions (and all three columns, not just the two selected above) and then you can just select the value for table1 to get the same result.

于 2013-03-16T09:27:34.943 回答