mysql,执行一个选择和过滤结果的查询

pxy2qtax  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(261)

我有一张这样结构的table:

  1. id seller class ref color pricekg
  2. 1 manta apple apple-red red 0.147
  3. 2 manta pear pear-green green 0.122
  4. 3 poma apple apple-red red 0.111
  5. 4 arnie melon melon-green green 0.889
  6. 5 pinas pineapple pinneaple-brown brown 0.890
  7. 6 gordon apple apple-red red 0.135

我需要从一些卖家那里买一些水果,有一些偏好。
我的第一个目标是知道谁卖我要找的东西,在我知道之后,挑一个最好的。
当我做第一个查询时,我得到:
查询->

  1. SELECT *
  2. FROM `fruits`
  3. WHERE `seller`
  4. IN ("manta", "poma", "pinas", "gordon")
  5. AND `class` IN ("apple", "pineapple")
  6. ORDER BY id

结果1->

  1. 1 manta apple apple-red red 0.147
  2. 3 poma apple apple-red red 0.111
  3. 5 pinas pineapple pinneaple-brown brown 0.890
  4. 6 gordon apple apple-red red 0.135

到目前为止还不错,但我有3个卖家谁有红苹果的苹果红参考。
这是我无法解决的部分。。。
根据这个结果,我想过滤重复的apples refs(因为我想从一个卖家那里购买)。
如果有重复的,选择一个卖家manta。
如果有复制品,而且没有一个是卖螳螂的,那就选一个每公斤成本最低的。
因此,在结果1之后,第二个查询(或子查询,或者如果有一种方法可以在一个查询中完成这一切,我真的不知道最好的方法是什么)的预期结果是:

  1. 1 manta apple apple-red red 0.147
  2. 5 pinas pineapple pinneaple-brown brown 0.890

如果曼塔不卖这些,那就是:

  1. 3 poma apple apple-red red 0.111
  2. 5 pinas pineapple pinneaple-brown brown 0.890

只有一个查询可以做到这一点吗?或者我可以从结果或时态表中创建一个视图,然后再执行一个查询来过滤重复项。我怎么能这么做?

slhcrj9b

slhcrj9b1#

这是一个优先级查询。
我想你想要:

  1. select f.*
  2. from fruits f
  3. where f.seller in ('manta', 'poma', 'pinas', 'gordon') and
  4. f.class in ('apple', 'pineapple') and
  5. f.id = (select f2.id
  6. from fruits f2
  7. where f2.seller in ('manta', 'poma', 'pinas', 'gordon') and
  8. f2.class in ('apple', 'pineapple') and
  9. f2.ref = f.ref
  10. order by (f2.seller = 'manta') desc, -- put manta sellers first
  11. f2.price asc -- then order by lowest price
  12. limit 1
  13. );

相关问题