首页 > 解决方案 > php mysql 从数据库中的三个表中选择信息

问题描述

客户搜索是通过卡号进行的(见表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'

现在我公开我的表格然后我解释我的问题

表A客户:它包含成员的信息

id_customer 姓名 卡号
1 卢卡 1234567890
2 标记 9876543210

表 B 积分:它包含累积的积分和产生的成本

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 中的点总和?如何在选择中添加它?

标签: php

解决方案


如果你想要一个请求来获取你需要的所有信息,你可以像这样发出子请求:

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表格提出单独的请求。


推荐阅读