如何重复查询元素?

时间:2016-02-04 14:20:28

标签: sql sqlite

考虑表

CREATE TABLE `contact` (
    `id`    INTEGER,
    `name`  TEXT,
    `category`  INTEGER,
    `freed` INTEGER DEFAULT 0,
    PRIMARY KEY(id)
);

我想创建这样的查询或视图,它将复制freed = 1 AND caregory IS NOT NULL行,因为这些行类别应设置为-1。应删除(category is null and freed = 1)行。

第一张图显示数据来源。第二张图片显示了期望的结果 应添加3个新行(Jin,-1,1 | Tih,-1,1 | Traph,-1,1)
1 raw被删除(Traph,null,1)

enter image description here

    WHERE NOT(category is null and freed = 1)
    ORDER BY category IS NULL ASC, category = -1 ASC, category ASC , name ASC

enter image description here

是否可以制作类似

的内容
CREATE VIEW v1 AS
SELECT s.name, s.category, s.freed
FROM contact s
CASE freed = 1 and category is not null 
    insert into v1(t.name,-1,1) 
    SELECT p.name
    FROM contact p
    WHERE s.name = p.name

2 个答案:

答案 0 :(得分:1)

如果您只想要这些值,那么:

select name, category, freed
from contact c
where category is null and freed = 1
union all
select name, -1, freed
from contact
where category is not null and freed = 1;

主要问题是获得正确的id值。这在SQLite中有点棘手,你的例子用#34;回填"数字根本不易实施。

答案 1 :(得分:0)

所以你需要的是:

INSERT INTO CONTACT 
(SELECT Name,-1,1 FROM CONTACT
WHERE CATEGORY IS NOT NULL AND FREED = 1)

删除:

DELETE FROM CONTACT
WHERE CATEGORY IS NULL AND FREED = 1

或者如果你想在查询中那么:

SELECT Name,-1,1 FROM CONTACT
WHERE CATEGORY IS NOT NULL AND FREED = 1
UNION 
select nam,ecategory,freed
FROM CONTACT