我有一个添加请求:
INSERT INTO LIKES_PRODUCTS AS L (L.USER_ID, L.PRODUCT_ID) VALUES('7', '1')
请求表中的行数:
SELECT COUNT(L.USER_ID) AS LIKES FROM LIKES_PRODUCTS AS L
是否可以将它们组合成一个查询,以便首先进行添加,然后仅对表中的行进行计数?
答案 0 :(得分:4)
您可以使用data modifying CTE
with new_row as (
insert into likes_products (user_id, product_id)
values (7,1)
)
select count(user_id) as likes
from likes_products;
但是,最后的select
看不到前CTE的影响。如果您总是插入一行,则只需在选择中插入count(user_id) + 1
。另一种选择是返回插入的行并将其添加到计数中:
with new_rows as (
insert into likes_products (user_id, product_id)
values (7,1),(8,2)
returning *
)
select count(user_id) + (select count(*) from new_rows) as likes
from likes_products;