簡體   English   中英

php mysql 從數據庫中的三個表中選擇信息

[英]php mysql select information from three tables from the database

客戶搜索是通過卡號進行的(見表A客戶),我使用的代碼是這樣的:

$id = $_POST['card_number'];
SELECT e.*, sum(u.points) as points, sum(u.cost) as cost,
max(date_format(u.date_points, '%e/%c/%Y')) as data
FROM `customer` AS e 
    INNER JOIN `points` AS u ON e.id_customer = u.id_customer 
where card_number='$id'

現在我公開我的表格,然后我解釋我的問題

Table A Customer:包含會員信息

id_customer 姓名 卡號
1 盧卡 1234567890
2 標記 9876543210

Table B Points:包含累積的點數和產生的費用

id_points id_customer 積分 成本
1 1 5 20
2 2 10 40
3 1 20 60
4 2 35 35

結果:

customer with id_customer 1 has a total of 25 points
customer with id_customer 2 has a total of 45 points

表C 扣除點數:包含下次購買時扣除的點數

id_deducted id_customer 積分
1 1 5
2 2 15

結果:

customer with id_customer 1 straight 5 points total remaining 20 points
customer with id_customer 2 climbs 15 points, total remaining 30 points

我的問題是,如何計算表 B 中的點總和 - 表 c 中的點總和? 我如何將它添加到選擇中?

如果你想要一個請求來獲取你需要的所有信息,你可以像這樣發出子請求:

SELECT
    c.*,
    (
      SELECT
        SUM(p.points)
      FROM
        points p
      WHERE
        p.id_customer = c.id_customer
    ) AS points,
    (
      SELECT
        SUM(d.points)
      FROM
        deducted_points d
      WHERE
        d.id_customer = c.id_customer
    ) AS deducted_points
FROM
    customer c;

結果如下

id_customer 姓名 卡號 積分 扣除點數
1 盧卡 1234567890 25 5
2 標記 9876543210 45 15

但是我認為對於大量用戶和積分變化來說會非常慢。 所以我會從用戶中進行選擇,然后循環遍歷他們,向points表和deducted_points表發出單獨的請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM