0
Table Name: free_meals_bill

punch_date                   employee_id  employee_name product_name
2021-02-22 12:15:50.086471   123456       john          Variety Rice - Curd - Rs.35
2021-02-22 12:19:50.086472   234456       marry         Variety Rice - Curd - Rs.35
2021-02-22 12:22:50.086473   355456       peter         Variety Rice - Curd - Rs.35

在插入“free_meals_bill”表之前,我想检查每个employee_id 是否只允许打一拳。例如,如果 john(员工 id 123456)已经在 free_meals_bill 中,那么在同一日期,john 数据不应再次插入到“free_meals_bill”表中。

询问:

 insert into free_meals_bill (punch_date,employee_id,employee_name,product_name)
 Values ('2021-02-22 10:15:50.086471',123456,'john','Variety Rice - Curd - Rs.35')
 SELECT
 employee_id,
 COUNT(*) as count,
 date_trunc('day',punch_date) as day
 FROM bill_item
 WHERE punch_date>= CURRENT_DATE
 GROUP BY employee_id, day 
 HAVING COUNT(*) = 0
4

3 回答 3

1

您可以使用 NOT EXISTS 条件来检查要插入的值是否已经存在:

insert into free_meals_bill (punch_date, employee_id, employee_name, product_name)
select *
from (
   values (date '2021-02-22 10:15:50.086471',123456,'john','Variety Rice - Curd - Rs.35')
) as t(punch_date, employee_id, employee_name, product_name
where not exists (SELECT *
                  FROM free_meals_bill bi
                  WHERE bi.punch_date::date = t.punch_date::date
                    AND bi.employee_id = t.employee_id)

但是如果你只允许每行(employee_id, punch_date)你应该创建一个唯一的约束或索引

create unique index only_one_meal_per_day
  on free_meals_bills ( (punch_date::date), employee_id);

然后你可以这样做:

insert into free_meals_bill (punch_date, employee_id, employee_name, product_name)
values (date '2021-02-22 10:15:50.086471',123456,'john','Variety Rice - Curd - Rs.35')
on conflict ((punch_date::date), employee_id)
do nothing;
于 2021-02-22T09:05:55.047 回答
0

您的 select 语句的列顺序错误,它应该与您的 insert 语句的顺序相同。日期、ID、名称、产品。而且,列数也应该相同。

于 2021-02-22T07:56:45.030 回答
0

演示:db<>小提琴

  1. 您不能在一个语句中使用VALUESand 。声明替换部分SELECTINSERTSELECTVALUES

  2. 您可以使用它EXISTS来检查是否出现。

    INSERT INTO free_meals_bill (punch_date,employee_id,employee_name,product_name)
    SELECT
        *
    FROM bill_item
    WHERE punch_date >= CURRENT_DATE
        AND NOT EXISTS (
           SELECT 1 FROM free_meals_bill WHERE employee_id = bill_item.employee_id
        );
    

注意:我*在这里使用了选择器,因为在我的示例bill_item中与free_meals_bill. 当然,如果它不适合这样的事情(取决于bill_item实际的样子),您必须将其调整为您的实际用例:

SELECT
    punch_date,
    employee_id,
    employee_name,
    product_name
...

编辑

为了避免表设计的这种重复,您应该考虑在UNIQUE表中添加一个约束:

ALTER TABLE free_meals_bill ADD CONSTRAINT my_unique_constraint UNIQUE (employee_id);

这可以防止INSERT语句自动插入重复记录,您不需要对SELECT语句执行此操作

于 2021-02-22T08:00:11.140 回答