sqlite查询,为什么它返回所有内容

时间:2013-08-13 20:06:06

标签: java sql sqlite

我正在使用此查询

  

query =“SELECT * FROM ri UNION SELECT * FROM pj UNION SELECT * FROM   td UNION SELECT * FROM cert UNION SELECT * FROM outros WHERE grupo =   'Grupo 1'“;

我试过像'Grupo 1'这样的grupo,但是也没用过

为什么它从列grupo返回所有内容,我只想要与grupo 1匹配的结果

!!

和另一个追加问题,如何复制file.db + date ... im planing每天做一个文件的备份,在另一个文件夹中复制它与当天的日期

2 个答案:

答案 0 :(得分:1)

WHERE运算符的优先级高于UNION。您的查询实际上是:

SELECT * FROM ri 
UNION 
SELECT * FROM pj 
UNION 
SELECT * FROM td 
UNION 
SELECT * FROM cert 
UNION 
SELECT * FROM outros WHERE grupo = 'Grupo 1'

WHERE子句仅适用于最终SELECT * FROM outros。您需要将WHERE添加到每个具有grupo列的子查询中(您没有指定哪个,所以我会假设全部):

SELECT * FROM ri WHERE grupo = 'Grupo 1'
UNION 
SELECT * FROM pj WHERE grupo = 'Grupo 1'
UNION 
SELECT * FROM td WHERE grupo = 'Grupo 1'
UNION 
SELECT * FROM cert WHERE grupo = 'Grupo 1'
UNION 
SELECT * FROM outros WHERE grupo = 'Grupo 1'

或者您可以使用这样的子查询(未经过测试,语法可能已关闭,抱歉):

SELECT * FROM 
(
    SELECT * FROM ri 
    UNION 
    SELECT * FROM pj 
    UNION 
    SELECT * FROM td 
    UNION 
    SELECT * FROM cert 
    UNION 
    SELECT * FROM outros 
)
WHERE grupo = 'Grupo 1'

顺便说一句,您可能不希望在*选择中使用UNION,因为如果其中一个表架构发生更改,则查询将失败。如果可能,最好明确选择所有列。

答案 1 :(得分:0)

如果每个表中都有grupo,那么每个SELECT都需要一个WHERE子句。现在,唯一被过滤的查询是SELECT * FROM outros

这是一些修改代码。 BTQ:请不要在现实生活中使用SELECT * ....

SELECT * 
FROM ri 
WHERE grupo = 'Grupo 1'
UNION 
SELECT * 
FROM pj 
WHERE grupo = 'Grupo 1'
UNION 
SELECT * 
FROM td 
WHERE grupo = 'Grupo 1'
UNION 
SELECT * 
FROM cert 
WHERE grupo = 'Grupo 1'
UNION 
SELECT * 
FROM outros 
WHERE grupo = 'Grupo 1'