繁体   English   中英

内部条件在哪里存在SQL?

[英]Where exists SQL with internal where condition?

我有以下要求,以更精确地说SQL参数化查询:

select * from `products` 
where (exists (select * from `productslocation` where `products`.`Id` = `productslocation`.`Product_Id` and `Country_Id` = ?) and 
exists (select * from `productprices` where `products`.`Id` = `productprices`.`Products_Id` and `Price` >= ?) 
and `Organization_Id` = ? and `name` like ? or `Description` like ?) and `Status` = ?

该查询仅使用运算符WHERE EXISTS检索存在country price产品。

如果找到它,则对第一个子查询返回TRUE ,然后对其余两个查询WHERE 第一个子查询返回TRUE ,第二个给出TRUE ,因为子查询也正确。 result = TRUE * TRUE = TRUE 但这是错误的结果。

问题是,需要使用两个内部查询WHERE来获取WHERE EXISTS结果。

这是否意味着我需要替换JOIN'S WHERE EXISTS 还是可以修改上面的查询?

这样不是更好吗? 尝试这个:

select * from `products` inner join productprices on `products`.`Id` = `productprices`.`Products_Id`
INNER JOIN `productslocation` ON `products`.`Id` = `productslocation`.`Product_Id`
where (`Organization_Id` = ? and `name` like ? or `Description` like ?) and `Status` = ? 
AND `productprices`.`Price` >= ?
and `productslocation`.Country_Id` = ?

您错过了或声明的方括号:

select * from `products` 
where (exists (select * from `productslocation` where `products`.`Id` = `productslocation`.`Product_Id` and `Country_Id` = ?) and 
exists (select * from `productprices` where `products`.`Id` = `productprices`.`Products_Id` and `Price` >= ?) 
and `Organization_Id` = ? and (`name` like ? or `Description` like ?)) and `Status` = ?

您的括号以及OR AND使得该语句非常复杂。
尝试这个:

    select * from `products` 
    where 
    (
    exists (select * from `productslocation` where `products`.`Id` = `productslocation`.`Product_Id` and `Country_Id` = ?) and 
    exists (select * from `productprices` where `products`.`Id` = `productprices`.`Products_Id` and `Price` >= ?) and 
    `Organization_Id` = ? and (`name` like ? or `Description` like ?) and `Status` = ?
    )

您正在寻找一个查询,该查询可以根据各种条件过滤products ,其中一些涉及引用关系。

假设您与参照表具有1-1关系,那么您应该可以使用JOIN

select *
from 
    `products` 
    inner join `productslocation` 
        on `products`.`Id` = `productslocation`.`Product_Id` and `productslocation`.`Country_Id` = ?
    inner join `productprices` 
        on  `products`.`Id` = `productprices`.`Products_Id` and `productprices`.`Price` >= ?
where
    `products`.`Organization_Id` = ? 
    and `products`.`name` like ? 
    and `products`.`Description` like ?
    and `products`.`Status` = ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM