[英]I want to fetch rows in a first table that are not in a second table
I have a table, let's call it fees
, and two other tables, let's call them transactions
and breakdowns
. 我有一个表,我们称它为“ fees
,还有另外两个表,我们称它们为“ transactions
和breakdowns
。
transactions
table saves the general summary of payments received while breakdowns
table saves the breakdown of the payments. transactions
表保存收到的付款的一般摘要, breakdowns
保存付款的明细。
breakdowns table looks something like this 故障表看起来像这样
id | transaction_id | fee_id
and fees table looks something like this 和费用表看起来像这样
id | amount | description
I'd like to fetch the fees in fees table that do not have records in breakdowns table based on the transaction_id 我想根据Transactions_id在费用明细表中获取没有明细表中记录的费用
SELECT * FROM fees LEFT JOIN breakdowns ON (fees.id = breakdowns.fee_id)
WHERE breakdowns.transaction_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
The code above returns empty rows 上面的代码返回空行
Use not exists
: 使用not exists
:
SELECT f.*
FROM fees f
WHERE NOT EXISTS (SELECT 1
FROM breakdowns b
WHERE b.fee_id = f.id AND
b.transaction_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
);
You can use a LEFT JOIN
as well, moving the condition on breakdowns
to the ON
clause: 您也可以使用LEFT JOIN
,将breakdowns
条件移至ON
子句:
SELECT *
FROM fees f LEFT JOIN
breakdowns b
ON b.fee_id = f.id AND
b.transaction_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
However, I think NOT EXISTS
more directly captures the logic you want. 但是,我认为NOT EXISTS
更直接地捕获您想要的逻辑。 Also, I see no reason to return the NULL
values for the columns in breakdowns
. 另外,我认为没有理由为breakdowns
的列返回NULL
值。
try this 尝试这个
$data['showrecord'] = DB::table('fees')
->where('breakdown.transaction_id',"=",'xxxxx')
->leftjoin('breakdown', 'breakdown.fee_id', '=', 'fees.id')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.