我有一个如下所示的mssql查询:
make -j
我将内部选择转换为Laravel查询生成器
SELECT * FROM (
SELECT a.Client, ad.Kto, a.Address, a.Matchcode, a.Name1, a.country, a.ZIP, a.Street FROM [HeadQuarter].[dbo].[Addresses] a
INNER JOIN [HeadQuarter].[dbo].[AddressesDetails] ad ON (a.Client = ad.Client AND
a.Address = ad.Address)
WHERE ad.Active <> 0 AND
(a.USER_emailactive = 0 OR a.USER_emailactive IS NULL)
) client_id
WHERE (a.Country = 'AT' AND a.ZIP BETWEEN '0000' AND '5000')
,这正在起作用。但是现在我如何获得
\DB::connection('sqlsrv')
->table('[HeadQuarter].[dbo].[Addresses]')
->join([HeadQuarter].[dbo].[AddressesDetails], function($join){
$join->on('[HeadQuarter].[dbo].[Addresses].Client', '=', '[HeadQuarter].[dbo].[AddressesDetails].Client')
->on('[HeadQuarter].[dbo].[Addresses].Address', '=', '[HeadQuarter].[dbo].[AddressesDetails].Address')
})
->select('[HeadQuarter].[dbo].[Addresses].Client, [HeadQuarter].[dbo].[AddressesDetails].Kto,....')
->where('[HeadQuarter].[dbo].[AddressesDetails].Active', '<>', '0')
->whereRaw('(a.USER_emailactive = 0 OR a.USER_emailactive IS NULL)')
->get();
转换为我的查询生成器。确保我可以使用-> select()并编写原始sql查询,但是我需要在查询生成器中使用它,因为我的内部和外部where子句我是可选的
答案 0 :(得分:0)
我想您可以按照以下方式简化查询,不需要子查询
SELECT a.Client, ad.Kto, a.Address, a.Matchcode, a.Name1, a.country, a.ZIP, a.Street
FROM [HeadQuarter].[dbo].[Addresses] a
INNER JOIN [HeadQuarter].[dbo].[AddressesDetails] ad
ON (a.Client = ad.Client AND a.Address = ad.Address)
WHERE ad.Active <> 0
AND a.Country = 'AT'
AND a.ZIP BETWEEN '0000' AND '5000'
AND (a.USER_emailactive = 0 OR a.USER_emailactive IS NULL)
在查询构建器中,您可以使用Parameter Grouping
\DB::connection('sqlsrv')
->table('[HeadQuarter].[dbo].[Addresses] as a')
->join('[HeadQuarter].[dbo].[AddressesDetails] as b', function($join){
$join->on('a.Client', '=', 'ad.Client')
->on('a.Address', '=', 'ad.Address');
})
->select('a.Client', 'ad.Kto', 'a.Address', 'a.Matchcode', 'a.Name1', 'a.country', 'a.ZIP', 'a.Street')
->where('ad.Active', '<>', '0')
->where(function ($query) {
$query->whereNull('a.USER_emailactive')
->orWhere('a.USER_emailactive', '=', '0');
})
->where(function ($query) {
$query->orWhere(function ($query) {
$query->where('a.Country', '<>', 'AT')
->whereBetween('a.ZIP', ['0000', '5000']);
})->orWhere(function ($query) {
$query->where('a.Country', '<>', 'Foo')
->whereBetween('a.ZIP', ['0000', '5000']);
})->orWhere(function ($query) {
$query->where('a.Country', '<>', 'Bar')
->whereBetween('a.ZIP', ['0000', '5000']);
});
})
->get();