MySQL 或 JPQL 查询从 OneToMany 关系中获取不同的值(条件优先级)

MySQL or JPQL query for getting different values from OneToMany relation (Condition priority)

我有一个 table 产品,其中包含

等信息
id product_name retailer_name
1 衬衫 古驰

此 table 与 product_prices 有一对多连接,其中包含

等信息
id 价格 国家 product_id
100 95.5 英国 1
101 97.5 法国 1
300 70.9 EUROPEAN_UNION 1

我需要创建一个 MySQL 或 JPQL 查询来检索

  1. product_name
  2. retailer_name
  3. 价格(根据国家或选择欧盟)

So for example: In case country United Kingdom is chosen -> then it will retrieve:

  1. Shirt Gucci 95.5

In case country Italy is chosen -> then it will retrieve:

  1. Shirt Gucci 70.9

As you can remark, in the second example, system retrieved EUROPEAN_UNION price because Italy could not be found.

In case country EUROPEAN_UNION is chosen -> then it will retrieve:

  1. Shirt Gucci 70.9

As you can remark, in the third example, system retrieved EUROPEAN_UNION price because EUROPEAN_UNION country was found.

我怎样才能做到这一点?

我在 JPQL 中尝试过类似的东西:

select new com.ProductDTOWithPrice(p.id, p.product_name, p.retailer_name, " +
        "pr.price) " +
        "from Product p " +
        "join ProductPrice pr " +
        "where p.id =:productId and (case when pr.country=:country then 1 " +
        "else when pr.country.id = EUROPEAN_UNION then 1 end)"

此外,尝试过进行多选或使用 exists,但我仍然无法弄清楚。我在检索“'price'”时卡住了。

    select p.id, p.name,
       Max(IF(pp.country_id = :countryId, true, false)) as mainCountry,
       Max(IF(pp.country_id = 400, true, false)) as europeanCountry
from products p
         join product_prices pp on p.id = pp.product_id
where p.id = '0002fb8977754949bf4da70535e1a2e6'
GROUP BY p.id;

有什么帮助吗?

我已经使用 MYSQL 解决了这个问题:

SELECT p.id, 
       p.name, 
       pp.price, 
       country, 
       (CASE WHEN (pp.country_id = :country      ) THEN 3
             WHEN (pp.country_id = EUROPEAN_UNION) THEN 2                                        
             ELSE 0 END                                  ) AS priorityIndex
FROM       products p
INNER JOIN product_prices pp 
        ON p.id = pp.product_id
WHERE p.id  = '0002fb8977754949bf4da70535e1a2e6'
ORDER BY priorityIndex DESC
LIMIT 1;

如果有人知道更好的解决方案,请告诉我。