如何简化此查询?不幸的是,这不起作用
$Query = mysqli_query($conn, "SELECT * FROM order_number where trans_id NOT IN (SELECT order_no from billing)
AND NOT IN(SELECT order_no from pending)
AND NOT IN(SELECT order_no from on_process)
AND NOT IN(SELECT order_no from finished)");
还有其他方法吗?我试图打印trans_id行,如果它不在开票,待处理,on_process和完成。
答案 0 :(得分:2)
SELECT * FROM order_number
where trans_id NOT IN
(
SELECT order_no from billing
union
SELECT order_no from pending
union
SELECT order_no from on_process
union
SELECT order_no from finished
)
或当你尝试它时
SELECT * FROM order_number
where trans_id NOT IN (SELECT order_no from billing)
AND trans_id NOT IN (SELECT order_no from pending)
AND trans_id NOT IN (SELECT order_no from on_process)
AND trans_id NOT IN (SELECT order_no from finished)
答案 1 :(得分:1)
没有理由“简化”查询。通过四个子查询中的表的适当索引,它应该非常有效。如果orderno
在任何表格中都可以NULL
,那么我建议改为使用not exists
:
SELECT *
FROM order_number o
WHERE NOT EXISTS (select order_no from billing where b.order_no = o.trans_id) AND
NOT EXISTS (select order_no from pending p where p.order_no = o.trans_id) AND
NOT EXISTS (select order_no from on_process op where op.order_no = o.trans_id) AND
NOT EXISTS (select order_no from finished f where f.order_no = o.trans_id);
正确的索引包括:billing(order_no)
,pending(order_no)
,finished(order_no)
和on_process(order_no)
。
答案 2 :(得分:0)
您可以在表上进行左连接,并过滤掉没有匹配记录的记录:
select
n.*
from
order_number n
left join billing b on b.order_no = n.trans_id
left join pending p on p.order_no = n.trans_id
left join on_process o on o.order_no = n.trans_id
left join finished f on f.order_no = n.trans_id
where
b.order_no is null and
p.order_no is null and
o.order_no is null and
f.order_no is null