0

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

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

  • 客户:身份证、姓名
  • 购买:id、customer_id、日期

从这里的这个问题SQL join: selection 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
4

1 回答 1

0

好吧,鉴于您的问题(查找给定客户的最新购买),那么您只想按日期对购买表进行搜索并限制为一个:

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

但是,您链接到的答案是找到所有客户及其最近的购买。在这种情况下,我可能会使用自定义 SQL 查询(尽管从技术上讲,您可以使用 Propel 函数执行此操作,但这会更加困难并且不会让您获得太多,因为您不会为对象补水(至少,不容易)。

更新这里有一些关于手动查询的信息。请注意,这样做时,返回的数据不会是 Propel 对象,但您可以根据需要进行按需补水

例子:

$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['...'];
    }
}
于 2013-06-03T16:18:30.223 回答