Propel 1.6每组最大n

时间:2013-05-31 13:16:22

标签: greatest-n-per-group propel

我需要构建可以获得客户最新购买的推进查询

请在答案中使用这些表/列名称:

  • customer:id,name
  • 购买:id,customer_id,date

来自这个问题SQL join: selecting the last records in a one-to-many relationship

我需要根据以下查询之一构建推进查询:

SELECT c.*, p1.*
FROM customer c
JOIN purchase p1 ON (c.id = p1.customer_id)
LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
    (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
WHERE p2.id IS NULL;

SELECT  c.*, p.*
FROM    customer c INNER JOIN
        (
            SELECT  customer_id,
                    MAX(date) MaxDate
            FROM    purchase
            GROUP BY customer_id
        ) MaxDates ON c.id = MaxDates.customer_id INNER JOIN
        purchase p ON   MaxDates.customer_id = p.customer_id
                    AND MaxDates.MaxDate = p.date

1 个答案:

答案 0 :(得分:0)

好吧,考虑到你的问题(找到给定客户的最新购买),你只想在购买表上按日期排序并限制为一个:

$lastPurchase = PurchaseQuery::create()
  ->filterByCustomerId($customerId)
  ->orderByDate(Criteria::DESC)
  ->limit(1)
  ->find();

然而,您链接的答案是找到所有客户及其最新购买。在这种情况下,我可能会使用自定义SQL查询(虽然从技术上讲,你可以使用Propel函数进行此操作,但这样做会更加困难,因为你不会保护对象(至少不容易),因此不会对你产生很大影响。

UPDATE 以下是doing a manual query的一些信息。请注意,执行此操作时,返回的数据将不是Propel对象,但如果需要,您可以执行on-demand hydration

示例:

$sql = "SELECT c.*, p1.*
        FROM customer c
        JOIN purchase p1 ON (c.id = p1.customer_id)
        LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
            (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
        WHERE p2.id IS NULL;";
$conn = Propel::getConnection(CustomerPeer::DATABASE_NAME);
$stmt = $conn->prepare($query);
if ($stmt->execute()) {
    while($result = $stmt->fetch()) {
        $someField = $result['...'];
    }
}