查询未返回正确的数据

3npbholx  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(267)

付款明细表

payment_detail_id| payment_id | payment_status | total | user_id | company_id
10001            |          10|    1           | 100        1          103
10002            |          11|    2           | 200        1          103
10003            |          12|    2           | 300        2          104
10004            |          13|    1           | 400        2          104
10005            |          14|    0           | 500        1          105
10006            |          15|    2           | 600        1          103

付款表

payment_id| payment_type| 
10        |          1  |    
11        |          1  |    
12        |          1  |    
13        |          1  |    
14        |          0  |    
15        |          0  |

如何获得 user_id 那些有 payment_type1 以及 payment_type0Payment_Table ?
这样做的目的是发现他们已经支付了两种类型的款项,而对于那些支付了其中两种款项的人来说,他们一定已经支付了 payment_status2 ,但如果例如 user_id1 以及 company_id103 ,输出必须为 100+200+600=900 .
此用户与此 company_id
payment_Type 0 以及 1 对于这两个条件 (payment_type=1 and payment_type=0) 成功地完成了它们 payment_Status2 即使你之前没有付款
例如 payment_detail_id1001payment_status1 .

eh57zj3b

eh57zj3b1#

SELECT
  DISTINCT user_id
FROM
  Payment_Detail_Table D
WHERE
  EXISTS(
    SELECT
      *
    FROM
      Payment_Table P1
    WHERE
      P1.payment_id = D.payment_id
    AND
      P1.payment_type = 1
  )
AND
  EXISTS(
    SELECT
      *
    FROM
      Payment_Table P2
    WHERE
      P2.payment_id = D.payment_id
    AND
      P2.payment_type = 0
   )
xzv2uavs

xzv2uavs2#

这就是你要找的吗?

SELECT user_id, company_id
FROM (select payment_detail_table.user_id AS user_id,payment_detail_table.company_id AS company_id
from payment_detail_table
where (EXISTS(SELECT * FROM payment_table WHERE payment_table.payment_id=payment_detail_table.payment_id AND payment_table.payment_type=1)) AND payment_detail_table.payment_status = 2
group by concat(payment_detail_table.user_id,'-',payment_detail_table.company_id)) T1
INNER JOIN
(SELECT payment_detail_table.user_id AS user_id,payment_detail_table.company_id AS company_id
FROM (select payment_detail_table.user_id AS user_id,payment_detail_table.company_id AS company_id
from payment_detail_table
where (EXISTS(SELECT * FROM payment_table WHERE payment_table.payment_id=payment_detail_table.payment_id AND payment_table.payment_type=0)) AND payment_detail_table.payment_status = 2
group by concat(payment_detail_table.user_id,'-',payment_detail_table.company_id)) T2
USING (user_id, company_id)

相关问题