我想从Postgres数据库中选择符合以下条件的行:
所以如果我有这样的表:
User | Item | Date -----+------+------ Fred | Ball | 5/1/2015 Jane | Pen | 5/7/2015 Fred | Cup | 5/11/2015 Mike | Ball | 5/13/2015 Jane | Ball | 5/18/2015 Fred | Pen | 5/20/2015 Jane | Bat | 5/22/2015搜索可能是"人们在买球后买了什么?"我想要的输出是:
User | Item | Date -----+------+------ Fred | Cup | 5/11/2015 Fred | Pen | 5/20/2015 Jane | Bat | 5/22/2015
我已经到了SELECT * FROM orders AS or WHERE or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
,这给了我所有弗雷德和简的订单(因为他们订购了多件事)。但是当我试图对WHERE子句施加额外的限制时(例如SELECT * FROM orders AS or WHERE or.item = 'Ball' AND or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
),我得到的东西根本不是我期望的 - 一个记录列表,其中item =' Ball&#39 ;这似乎忽略了查询的第二部分。
感谢您提供的任何帮助。
编辑:对不起,我最后通过描述我正在采取的糟糕方法误导了一些人。 (我正在努力获取Ball购买列表,我可以在下一步中将其用作子查询,但人们正确地指出这是一种不必要的复杂/昂贵的方法。)
答案 0 :(得分:0)
我认为这可能会给你想要的结果:
SELECT orders.user, orders.item, orders.date
FROM orders, (SELECT * FROM orders WHERE item = 'ball') ball_table
WHERE orders.user = ball_table.user AND orders.date > ball_table.date;
答案 1 :(得分:0)
select b.*
from user_table a
join user_table b
on b.user = a.user
and b.date > a.date
and b.item = 'Ball'
答案 2 :(得分:0)
SELECT DISTINCT t3.*
FROM mytable t1
INNER JOIN mytable t2
ON t1.Item = t2.Item AND t1.User <> t2.User
INNER JOIN mytable t3
ON t2.User = t3.User AND t2.Date <= t3.Date
WHERE t1.Item = "Ball"