mysql连接两个表选择并记录问题

时间:2012-06-10 15:00:41

标签: mysql pdo

我想在我的网页上显示以下信息:
日期 - 个人开支(营业费用)
06年6月6日 - usd555.00(usd3022.00)
2012年6月5日 - usd666.00(usd0.00)
04年6月4日 - usd0.00(usd444.40)
04年6月4日 - usd333.00(usd2333.40)

目前我的代码是:

$sql = "SELECT payment_date, sum(price) FROM expense WHERE category=? spender_id=? GROUP BY payment_date";
    $q = $conn->prepare($sql);
    $result = $q->execute(array("Personal", $user_id));
    while($r = $q->fetch(PDO::FETCH_ASSOC)){
        $payment_date_db = $r['payment_date'];
        $payment_date_db2 = date("d-F-Y", strtotime($payment_date_db));
        $price_db = $r['sum(price)'];

        echo $payment_date_db2 . " - " . $money_currency . $price_db . "<br />";
    }

我不知道如何选择和显示业务费用记录并将其显示在一揽子标志()中。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您应该提供有关表架构的更多详细信息,但我想我可以从您的查询中推断出它是这样的:

费用(payment_id [PK],spender_id [FK],类别[FK ??],价格,payment_date)

类别字段包含“个人”或“费用”。

因此,如果您想获得每个日期特定消费者的个人和商业费用总和,请尝试以下查询:

SELECT 
    payment_date,
    SUM(IF(category = 'Personal', price, 0)) AS personal_expense_total,
    SUM(IF(category = 'Business', price, 0)) AS business_expense_total
FROM 
    expense
WHERE 
    spender_id = ?
GROUP BY 
    payment_date

所以在你的PHP代码中,你可以这样做:

$sql = '
    SELECT
        payment_date,
        SUM(IF(category = "Personal", price, 0)) AS personal_expense_total,
        SUM(IF(category = "Business", price, 0)) AS business_expense_total
    FROM expense
    WHERE spender_id = :spender_id
    GROUP BY payment_date';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':spender_id', $user_id, PDO::PARAM_INT); // Assuming $user_id contains an integer
$stmt->execute();

while($r = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $date = date('d-F-Y', strtotime($r['payment_date']));
    $personal = 'usd' . number_format($r['personal_expense_total'], 2);
    $business = 'usd' . number_format($r['business_expense_total'], 2);

    echo "$date - $personal - ($business)<br />";
}