is it possible to create mysql query (Sort by column considering foreign columns)

StackOverflow https://stackoverflow.com/questions/19090294

  •  29-06-2022
  •  | 
  •  

문제

For example I have 2 tables:

product:
id: integer
price: integer

variation:
id: integer
product_id: integer
price integer

Some products have variations, some products don't have variations. I want to get all products, sorted by price. And if product has variation, this product must be sorted by first variation price, not its own price.

And is it possible to make such Propel Criteria or Query ?

도움이 되었습니까?

해결책

SELECT
*
FROM
product p
LEFT JOIN variation v ON p.id = v.product_id
ORDER BY COALESCE(v.price, p.price)

COALESCE() returns the first of its parameters which isn't NULL. The LEFT JOIN returns everything from product table, if there's no match on variation table, there's NULL.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top