SQL limit SELECT but not JOIN

后端 未结 2 896
北荒
北荒 2021-01-29 08:48

I\'m implementing pagination on my BD. My problem is when I want limit the SELECT statement but not the JOIN. Example, a product can got many prices:

SELECT * FR         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 09:13

    I would write a subquery to get the three first products (or whatever condition you choose) like this:

    SELECT id
    FROM product
    ORDER BY id
    LIMIT 3;
    

    Once I have that, I can select everything from the price table as long as the id is in that subquery. You can do this using a join:

    SELECT p.*
    FROM price p
    JOIN(
       SELECT id
       FROM product
       ORDER BY id
       LIMIT 3) tmp ON tmp.id = p.product_id;
    

    Here is an SQL Fiddle example using your sample data, and I also added a row that won't be returned so you can see that it works.

提交回复
热议问题