LINKs: https://www.2ndquadrant.com/wp-content/uploads/2019/05/sumtest.sql_.txt https://www.2ndquadrant.com/en/blog/join-lateral/
CREATE TABLE co_books (
dd numeric references books(dd),
pname text references persons(pname),
checked_out timestamptz,
checked_in timestamptz);
Do $$
DECLARE
i int;
afew int;
p record;
BEGIN
FOR p IN SELECT pname FROM persons LOOP
afew := (random() * 10)::integer;
FOR i in 0..afew LOOP
INSERT INTO co_books (dd, pname, checked_out)
VALUES
( (SELECT dd FROM books ORDER BY random() LIMIT 1),
p.pname, /* hint: fix bad random data here */
(SELECT xtime FROM X2018 ORDER BY random() LIMIT 1)
);
END LOOP;
END LOOP;
RETURN;
END;
$$;
If you follow the link, you can see it clearly that table person, column pname have 24 unique rows. After I executed the code block, then test how many rows in table: co_books. first time is 129 rows, then i delete the co_books, execute the code again, the rows is 156 rows, third time is 154 rows. So In this case, I think i don't understand the following part.
FOR p IN SELECT pname FROM persons LOOP
afew := (random() * 10)::integer;
FOR i in 0..afew LOOP