SQL limit SELECT but not JOIN

后端 未结 2 882
北荒
北荒 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:08

    Modify your query to limit the number of product rows before joining it to the price table. This means we want to to join the results of a query to a table, or in other words, we write a query containing a subquery:

    SELECT *
    FROM (
        SELECT *
        FROM product
        ORDER BY id_product
        LIMIT 3
    ) p
    LEFT JOIN price ON p.id = price.id_product
    

    Hope that helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题