简体   繁体   中英

How to implement loops in PostgreSQL

I am having a headache with implementing loops in my PostgreSQL query.

In my database I have two tables:

Table category
-----------------
pro_cat_id int,
pro_cat_name text

Table product_list
---------------------------------------------------
pro_id int,
pro_name text,
pro_cat_id int (foreign key to category.pro_cat_id)

I might have 5-6 value in category table. So I wrote a query, which looks like this

SELECT pro_id, pro_name, pro_cat_id
FROM pro_list
WHERE pro_cat_id = 65
LIMIT 18

UNION ALL 

SELECT pro_id, pro_name, pro_cat_id
FROM pro_list 
WHERE pro_cat_id = 80 
LIMIT 18

So what I want is to write one simple query using loop, so that the query would be dynamic.

So the value in categories might change. The admin can add some possible category value. If I would not use loop, the code would be static. To make it dynamic, I want to use loop

Loops in PostgreSQL are only available in stored procedures/functions. But I am not sure if you really need a loop for your problem:


demo: db<>fiddle (with limit == 5)

SELECT pro_id, pro_name, pro_cat_id 
FROM (
    SELECT 
        pro_id, 
        pro_name, 
        pro_cat_id, 
        row_number() OVER (PARTITION BY pro_cat_id) 
    FROM pro_list
    WHERE pro_cat_id IN (65, 80) -- changing the category list
)s
WHERE row_number <= 18           -- changing the product limit

You can simply change the pro_cat_id list in the inner WHERE clause. If you want to change the categories simply change this list. It depends on your backend code and how you are want to change the category ids: You should be able to pass a list or an array into the query as parameter. So your code can look as:

... WHERE pro_cat_id IN ?      -- for lists, as demonstrated
... WHERE pro_cat_id = ANY(?)  -- for arrays (see fiddle) 

To limit the products you can change the value in the outer WHERE clause.

The row_number() window function ( https://www.postgresql.org/docs/current/static/tutorial-window.html ) creates a row count for every category. So you can filter by the maximum row count.


Edit : Here is explained how to pass an array into an sql query in PHP

$sql = "<the query from above> WHERE pro_cat_id IN ('$categoryIds')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM