3

我正在为我的 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
4

1 回答 1

0

There is nothing wrong with your query. You're just there:

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

Here 1 and 0 are values (in your first case, true and false). First of all you should ensure there are fields Question 1 and Question 3 in your Questions table. Secondly the column count as well as data types of Scale table should match Questions table. Otherwise you will have to do selectively choose the fields in your SELECT query.

Edit: To respond to your edit, I am not seeing an elegant solution. You could do this:

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

Your insert did not work because ItemID cant be both 1 and 3 at the same time. My solution gets the required records to be inserted into Scale table, but verifies both the record exists by checking the count. Additionally you could (should) do as below since this can be marginally more efficient (the above SQL was to clearly show the logic being used):

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
于 2012-10-27T07:11:33.473 回答