2016-02-04 65 views
0

考慮表如何查詢重複的元素?

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個新的行應增加(金,-1,1 | TIH,-1,1 | Traph,-1,1)
1原料是souldbe刪除(Traph,空,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 
+1

不,但它可能就像我張貼在我的答案。視圖代表一個選擇查詢,它不能更新或插入。 – sagi

回答

0

那麼ÿ OU需要的是這樣的:

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 
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中有點棘手,而你的「回填」數字的例子根本不容易實現。

+0

請看問題的更新底部。是否有可能做出這樣的看法? – Yarh