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