我有以下要求,以更精确地说明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` = ?
此查询仅使用运算符country
检索price
,WHERE EXISTS
存在的产品。
如果找到,它将为第一个子查询返回TRUE
,然后处理其余两个查询WHERE
。第一个子查询返回TRUE
,第二个子查询返回TRUE
,因为子查询也正确。 result = TRUE * TRUE = TRUE
。但这是错误的结果。
问题是,WHERE EXISTS
的结果需要在两个内部查询中使用。
这是否意味着我需要在WHERE EXISTS
上替换JOIN'S
?还是可以修改上面的查询?
答案 0 :(得分:1)
那不是更好吗?试试这个:
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` = ?
答案 1 :(得分:1)
您错过了or语句的方括号:
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` = ?
答案 2 :(得分:1)
您的括号和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` = ?
)
答案 3 :(得分:0)
您正在寻找一个查询,该查询可根据各种条件过滤products
,其中一些条件涉及引用关系。
假设您与参照表具有1-1
关系,那么您应该可以使用JOIN
s:
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` = ?