MySQL Query with multiple LIMITS

前端 未结 5 729
甜味超标
甜味超标 2021-01-12 17:49

Let\'s say I have the following table with hundreds of toys of various colors...

---------------------------
  ITEM  |  COST  |  COLOR
----------------------         


        
相关标签:
5条回答
  • 2021-01-12 18:25

    For me the solution is create 3 different queries and merge the 3 arrays in PHP

    0 讨论(0)
  • 2021-01-12 18:26

    Well, IMHO, you were given 2 options here, however, I'll still go by merging the arrays as it won't take so many time/system resources like UNION. (Based on that you've said the table has a LOT of rows)

    0 讨论(0)
  • 2021-01-12 18:31

    ROW_NUMBER() could be used:

    SELECT *
    FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY COLOR ORDER BY COST) AS RN
          FROM TOYS
          WHERE COLOR IN ('YELLOW', 'WHITE', 'BLUE')) sub
    WHERE RN <= CASE COLOR WHEN 'YELLOW' THEN 1 WHEN 'WHITE' THEN 3 WHEN 'BLUE' THEN 2 END  
    
    0 讨论(0)
  • 2021-01-12 18:33

    Why not?

    select * from toys where color = 'Yellow' (LIMIT 1)
    UNION
    select * from toys where color = 'White' (LIMIT 3)
    UNION
    select * from toys where color = 'Blue' (LIMIT 2)
    
    0 讨论(0)
  • 2021-01-12 18:35

    This is working properly

    (select * from toys where color = 'Yellow' LIMIT 1)
    UNION ALL
    (select * from toys where color = 'White' LIMIT 1)
    
    0 讨论(0)
提交回复
热议问题