SQLite - 从视图更新

时间:2018-05-05 18:43:53

标签: sql sqlite view sql-update database-trigger

我有一个观点:


    CREATE VIEW UsersCounts AS SELECT
        users.id,
        users.username,
        users.email,
        SUM(CASE WHEN orders.id > 0 THEN 1 ELSE 0 END) as orders_all,
        SUM(CASE WHEN orders.status='ACTIVE' THEN 1 ELSE 0 END) as orders_active,
        SUM(CASE WHEN orders.status='RETURNED' THEN 1 ELSE 0 END) as orders_returned
    FROM users
        INNER JOIN orders ON
            users.email = orders.email
    GROUP BY users.id

结果:

id | username | email | orders_all | orders_active | orders_returned

如何将Users.customer_status = "VIP"'设置为orders_active > 5

3 个答案:

答案 0 :(得分:1)

示例:

从视图ID更新表 设定年龄< 18无法吸烟

create table TestTable (id int,age int,smokable NVARCHAR(8));
CREATE VIEW TestView AS SELECT
id,
case when age < 18 then 'young' 
else 'old'
end status
from TestTable;
insert into TestTable (id,age,smokable) values (1,25,null),(2,17,null),(3,12,null),(4,9,null);
select * from TestView;
id | status
:- | :-----
1  | old   
2  | young 
3  | young 
4  | young 
select * from TestTable;
id | age | smokable
:- | :-- | :-------
1  | 25  | null    
2  | 17  | null    
3  | 12  | null    
4  | 9   | null    
update TestTable
set smokable = 'Unable'
where id in (select id from TestView where status = 'young');
select * from TestTable;
id | age | smokable
:- | :-- | :-------
1  | 25  | null    
2  | 17  | Unable  
3  | 12  | Unable  
4  | 9   | Unable  

答案 1 :(得分:0)

对于更新,您可以使用

    UPDATE users 
    SET customer_status = 'VIP'
    where EXISTS ( SELECT orders_active
                   FROM orders_active
                   WHERE  users.email = email
                   AND  orders_active > 5
    )

答案 2 :(得分:0)

你会这样做:

CREATE VIEW UsersCounts AS
    SELECT u.id, u.username, u.email,
           SUM(CASE WHEN o.id > 0 THEN 1 ELSE 0 END) as orders_all,
           SUM(CASE WHEN o.status = 'ACTIVE' THEN 1 ELSE 0 END) as orders_active,
           SUM(CASE WHEN o.status = 'RETURNED' THEN 1 ELSE 0 END) as orders_returned,
           (CASE WHEN SUM(CASE WHEN o.status = 'ACTIVE' THEN 1 ELSE 0 END) > 5
                 THEN 'VIP'
                 ELSE MAX(u.customer_status)
            END) as customer_status
    FROM users u INNER JOIN
         orders o
         ON u.email = o.email
    GROUP BY u.id