仅显示mysql子查询返回null的行

时间:2015-02-19 20:47:12

标签: mysql sql

我正在尝试查询收据表,从第一笔交易属于特定时间范围的数据库中提取订单号。以下是我到目前为止的情况:

SELECT id, order_number, 
(
  SELECT id FROM receipts 
  WHERE received < r.received AND order_number = r.order_number 
  LIMIT 1
) priorPayment 
FROM receipts r 
WHERE received > 1416384000 AND received < 1416470399 
ORDER BY id DESC

这样可以正常工作,除非我想过滤掉任何返回了PriorPayment的东西(所以只显示这个子查询返回null的位置)现在它返回所有内容。有什么建议吗?

4 个答案:

答案 0 :(得分:1)

虽然您可以为此或having子句使用子查询,但我建议您只使用left join

SELECT r.id, r.order_number
FROM receipts r LEFT JOIN
     receipts r2
     ON r2.received < r.received and r2.order_number = r.order_number
WHERE r.received > 1416384000 AND r.received < 1416470399 AND
      r2.order_number is NULL
ORDER BY r.id DESC;

答案 1 :(得分:1)

另一种方法是将subqueryselect带入where子句:

SELECT id, order_number, null as priorPayment 
FROM receipts r 
WHERE received > 1416384000 AND received < 1416470399 
and (
  SELECT id FROM receipts 
  WHERE received < r.received AND order_number = r.order_number 
  LIMIT 1
) is null
ORDER BY id DESC

答案 2 :(得分:1)

为了获得更好的性能,我建议保留子查询(只选择你需要的3列)并将其与LEFT JOIN和IS NULL条件组合以获得预期的结果:

SELECT r.id, r.order_number
FROM receipts r 
left join (
SELECT id, received, order_number FROM receipts 
) priorPayment
ON priorPayment.received < r.received 
AND priorPayment.order_number = r.order_number
WHERE r.received > 1416384000 
AND r.received < 1416470399 
AND r.priorPayment.id is null
ORDER BY r.id DESC

答案 3 :(得分:1)

这是一种常见的写法:

SELECT r.id, r.order_number
FROM receipts r
WHERE r.received > 1416384000 AND r.received < 1416470399  
AND NOT EXISTS (SELECT id FROM receipts WHERE received < r.received AND order_number = r.order_number LIMIT 1)
ORDER BY r.id DESC

或者,在这种情况下,您可以使用反连接:

SELECT r1.id, r1.order_number
FROM receipts r1
LEFT JOIN receipts r2
  ON r2.order_number = r1.order_number AND r2.received < r1.received
WHERE r1.received > 1416384000 AND r1.received < 1416470399
  AND r2.order_number is NULL
ORDER BY r1.id DESC