SQLite比较两列

时间:2012-10-27 06:33:41

标签: sqlite insert

我正在为我的Psych课程创建一个数据库,我正在为个性档案打分。我需要比较两个测试项目,如果它们符合条件,则复制到一个单独的表中。

示例(伪代码在\之间)Sqlite3

INSERT INTO Scale
SELECT* FROM Questions
WHERE \\if Question 1 IS 'TRUE' AND Question 3 IS 'FALSE' THEN Copy this Question
and its response into the Scale table\\;

我还有大约100个其他问题。样本格式如下:

IF FirstQuestion IS value AND SecondQuestion IS value THEN 
Copy both questions into the Scale TABLE.

----------第一次回复后被编辑!编辑跟踪-------------

这是我的TestItems表:

ItemID |      ItemQuestion       | ItemResponse
```````````````````````````````````````````````````
   1   |    Is the sky blue?     |    TRUE
   2   |    Are you a person?    |    TRUE
   3   |    2 Plus 2 Equals Five |    FALSE

我想做什么:如果问题1为TRUE且问题3为FALSE,则将两个问题插入“Scale”表(其设置类似于TestItems)。我试过这个:

INSERT INTO Scale
SELECT * FROM TestItems
WHERE ((ItemID=1) AND (ItemResponse='TRUE')) 
AND ((ItemID=3) AND (ItemResponse='FALSE'));

但是:上面的INSERT都没有复制。 结果“比例”表应如下所示:

ItemID |      ItemQuestion       | ItemResponse
```````````````````````````````````````````````````
   1   |    Is the sky blue?     |    TRUE
   3   |    2 Plus 2 Equals Five |    FALSE

1 个答案:

答案 0 :(得分:0)

您的查询没有任何问题。你就在那里:

INSERT INTO Scale
SELECT * FROM Questions
WHERE `Question 1` = 1 AND `Question 3` = 0;

这里的1和0是值(在第一种情况下,是真和假)。首先,您应该确保Question 1表格中有字段Question 3Questions。其次,Scale表的列数和数据类型应与Questions表匹配。否则,您必须有选择地选择SELECT查询中的字段。

修改:要回复您的修改,我看不到优雅的解决方案。你可以这样做:

INSERT INTO Scale
SELECT * FROM TestItems WHERE ItemID = 1 AND ItemResponse = 'TRUE'
UNION
SELECT * FROM TestItems WHERE ItemID = 3 AND ItemResponse = 'FALSE'
WHERE (SELECT COUNT(*) FROM (
                             SELECT 1 FROM TestItems WHERE ItemID = 1 AND ItemResponse = 'TRUE'
                             UNION
                             SELECT * FROM TestItems WHERE ItemID = 3 AND ItemResponse = 'FALSE'
                            ) AS t) >= 2

您的插入无效,因为ItemID无法同时为1和3。我的解决方案将所需的记录插入到Scale表中,但通过检查计数来验证记录是否存在。另外,您可以(应该)执行以下操作,因为这可以稍微提高效率(上面的SQL是为了清楚地显示正在使用的逻辑):

INSERT INTO Scale
SELECT * FROM TestItems WHERE ItemID = 1 AND ItemResponse = 'TRUE'
UNION
SELECT * FROM TestItems WHERE ItemID = 3 AND ItemResponse = 'FALSE'
WHERE (
       SELECT COUNT(*) 
       FROM   TestItems 
       WHERE  ItemID = 1 AND ItemResponse = 'TRUE' 
           OR ItemID = 3 AND ItemResponse = 'FALSE'
      ) >= 2