查询与多个join /存在与不同where子句的相同关系

时间:2017-01-13 09:13:43

标签: php mysql laravel eloquent laravel-5.2

这是我的表

enter image description here 我希望product_id具有这两个条件

 `f_id` = '4' and `value` in ('10', '11', '12', '13' )

 `f_id` = '10' and `value` in ('34')

这将是product_id : 11 这是我的查询

$products = Product::whereHas('ProductFilter' , function($q) use ($filter_groups){

        foreach($filter_groups as $k=>$v)
        $q->where('f_id' , $k )->whereIn( 'value' ,$v );

    })->get();

将导致此查询

select * from `products` where exists 

( 
  select * from `product_filters` where 
 `product_filters`.`product_id` = `products`.`id` and 
 `f_id` = '4' and `value` in ('10', '11', '12', '13' )   and 
 `f_id` = '10' and `value` in ('34')

)

f_idvalue之间没有关系,也不会返回任何结果

基本上我想要的是这个查询

select * from `products` where exists 

( 
  select * from `product_filters` where 
 `product_filters`.`product_id` = `products`.`id` and 
 `f_id` = '4' and `value` in ('10', '11', '12', '13' )  

)
and exists 
( 
  select * from `product_filters` where 
 `product_filters`.`product_id` = `products`.`id` and 
 `f_id` = '10' and `value` in ('34')

)

2 个答案:

答案 0 :(得分:0)

您应该将其他条件写为子查询

select * from `products` where exists 

( 
  select * from `product_filters` where 
 `product_filters`.`product_id` = `products`.`id` and 
  (`f_id` = '4' and `value` in ('10', '11', '12', '13' ) ) and  `product_filters`.`product_id` in (select product_id from product_filters where `f_id` = '10' and `value` in ('34') )    
)

答案 1 :(得分:0)

Public Sub Main()

        Dim oExcel As Object
        Dim oBook As Object

        Dim sFileName As String
        Dim sFileNameOnly As String


        Dim sXlsPath As String
        Dim sTsvPath As String



        sFileName = CStr(Dts.Variables("User::Xls_File_Name").Value)


        sXlsPath = "H:\Xls_Files\" + sFileName

        sFileNameOnly = Path.GetFileNameWithoutExtension(sFileName)

        sTsvPath = "H:\Xls_Files\" + sFileNameOnly + ".Txt"


        oExcel = CreateObject("Excel.Application")


        oBook = oExcel.Workbooks.Open(sXlsPath)

        oBook.SaveAs(sTsvPath, -4158)

        oBook.Close(False)
    enter code here
        oExcel.Quit()

        Dts.TaskResult = ScriptResults.Success
    End Sub
相关问题