在MySQL
返回最后匹配的行我有这个表在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_from
和qty_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
最大数量我怎样才能做到这一点?
回答:
我解决这个问题。
感谢@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
我这个多次测试,我认为这就是答案
回答:
应当更新where条件来实现你想要的结果。更新后的查询将是 -
SELECT * FROM table WHERE p_id IN ('4', '5', '6') AND qty_from <= 10 AND qty_to >= 8
回答:
讨论后,这里是你需要(第一和未测试的解决方案):
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)
回答:
此解决方案:
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_ids表中取出,然后用行加入每个p_id最希望的id(如果16不在qty_from和qty_to范围内,则采用qty_to最大的那个)。
一个缺陷:如果多个行匹配范围条件,只有具有最大qty_to的一个被选择,所以每P_ID只有一个结果。我希望这对你来说已经足够了!
以上是 在MySQL 的全部内容, 来源链接: utcz.com/qa/263375.html