在Postgres

时间:2017-05-27 10:36:56

标签: postgresql

我有以下查询返回这两个元素。

SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method 
  FROM ticket_holds 
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id 
LEFT JOIN orders ON orders.id = order_items.order_id 
LEFT JOIN users ON users.id = orders.user_id 
LEFT JOIN charges on charges.order_id = orders.id;

这个结果没问题。

id |         created_at         | user_id | id | payment_method 
----+----------------------------+---------+----+----------------
  1 | 2017-05-26 04:29:22.189628 |       4 |  4 | 
  2 | 2017-05-26 04:33:00.721404 |       4 |  4 | some_payment_method

当我尝试过滤查询以显示每个用户创建的最后一条记录时,使用SELECT MAX也可以正常工作。

SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method 
  FROM ticket_holds 
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id 
LEFT JOIN orders ON orders.id = order_items.order_id 
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id 
WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id);

结果

 id |         created_at         | user_id | id | payment_method 
----+----------------------------+---------+----+----------------
  2 | 2017-05-26 04:33:00.721404 |       4 |  4 | some_payment_method
(1 row)

然而,当我尝试过滤以仅选择没有payment_method的项目时,我没有得到任何结果。

SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method 
  FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id 
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id 
LEFT JOIN charges on charges.order_id = orders.id 
WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id AND charges.payment_method IS NULL);

(注意AND charges.payment_method IS NULL)和查询结束)

这就是我得到的

 id | created_at | user_id | id | payment_method 
----+------------+---------+----+----------------
(0 rows)  

任何想法如何在没有付款方式的情况下检索元素,在这种情况下,将是ID为1的记录?

1 个答案:

答案 0 :(得分:1)

根据聊天讨论。我认为以下查询将帮助您获得所需的结果。

with data as ( SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method
FROM ticket_holds
LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id
LEFT JOIN orders ON orders.id = order_items.order_id
LEFT JOIN users ON users.id = orders.user_id
LEFT JOIN charges on charges.order_id = orders.id
where charges.payment_method is null

)
select * from data d1
where d1.created_at = (select max(created_at) from data d2
where d1.users_id = d2.user_id
)

在where子句中编写子查询时几点。请小心加入您的餐桌,因为您没有使用任何色谱柱加入。