返回mysql中最后一个匹配的行

时间:2016-12-22 08:35:48

标签: mysql

我有这张桌子

 id | qty_from | qty_to | p_id | price 
--------------------------------------
 1  |    1     |   10   |  4   | 1000  
--------------------------------------
 2  |    11    |   20   |  4   | 2000  
--------------------------------------
 3  |    1     |   10   |  5   | 500   
--------------------------------------
 4  |    11    |   20   |  5   | 1000  
--------------------------------------
 5  |    1     |   10   |  6   | 1000  
--------------------------------------
 6  |    10    |   15   |  6   | 2000  

我尝试使用以下代码qty_fromqty_to以及p_id获取行

SELECT * FROM table WHERE p_id IN ('4', '5', '6') AND qty_from <= 8 AND qty_to >= 8

返回第1行,第3行和第5行 当我使用这段代码时,它只返回第1行和第3行。

SELECT * FROM table WHERE p_id IN ('4', '5', '6') AND qty_from <= 16 AND qty_to >= 16

我也要回到第6行。因为它是p_id = 6中最大的数量 我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:1)

在讨论之后,您需要(首先未经测试的解决方案)

SELECT * 
FROM (SELECT *, MAX(qty_to) as max_qty_to FROM `limit`) T
WHERE p_id IN ('4', '5', '6') 
AND ( ( qty_from <= 16 AND qty_to >= 16 ) OR qty_to = T.max_qty_to )

答案 1 :(得分:0)

您应该更新您的位置条件以达到您想要的效果。更新的查询将是 -

SELECT * FROM table WHERE p_id IN ('4', '5', '6') AND qty_from <= 10 AND qty_to >= 8

答案 2 :(得分:0)

我只是解决了这个问题 感谢@Meloman给我的线索。

SELECT * FROM table WHERE p_id IN ('4', '5', '6') AND ((qty_from <= 16 AND qty_to >= 16) OR (qty_to, p_id) IN (SELECT dd.qty_to, dd.p_id FROM table dd INNER JOIN (SELECT MAX(qty_to) AS mm, p_id FROM table GROUP BY p_id) ddd ON dd.p_id = ddd.p_id AND dd.qty_to = ddd.mm WHERE dd.p_id IN ('4', '5', '6'))) GROUP BY p_id

我多次测试,我认为这是答案

答案 3 :(得分:0)

此解决方案有效:

SELECT DISTINCT t3.*
FROM `table` t1
LEFT JOIN `table` t2 ON t2.id=IFNULL(
    (SELECT id FROM `table` t3 
     WHERE t3.p_id=t1.p_id AND 16 BETWEEN t3.qty_from AND t3.qty_to 
     ORDER BY qty_to DESC LIMIT 1),
    (SELECT id FROM `table` t4 
     WHERE t4.p_id=t1.p_id 
     ORDER BY qty_to DESC LIMIT 1))
WHERE t1.p_id IN ('4', '5', '6')

基本上,首先获取具有给定p_id的表,然后将每个p_id与最期望的id的行连接(如果16不在qty_from和qty_to的范围内,则采用具有最大qty_to的行)。 / p>

一个缺陷:如果多行与范围条件匹配,则只选择具有最大qty_to的那一行,因此每个p_id只有一个结果。我希望这对你来说足够了!