Где существует SQL с внутренним, где условие? - PullRequest
0 голосов
/ 07 декабря 2018

У меня есть следующий запрос, точнее говоря, параметризованный запрос 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 для результата из WHERE EXISTS.

Означает ли это, что мне нужно заменить WHERE EXISTS ON JOIN'S?Или можно изменить запрос выше?

Ответы [ 4 ]

0 голосов
/ 07 декабря 2018

Ваши круглые скобки и OR s и AND s делают утверждение очень сложным.Попробуйте это:

    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` = ?
    )
0 голосов
/ 07 декабря 2018

Вы пропустили скобки вокруг вашего или утверждения:

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` = ?
0 голосов
/ 07 декабря 2018

Вы ищете запрос, который фильтрует 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` = ?
0 голосов
/ 07 декабря 2018

Так не лучше?Попробуйте это:

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` = ?
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...