Reputation: 51
I have a form in which I bring product names. I exclude the ones that are in another table.
SELECT ID_Produto, NomeProduto
FROM tbl_produtos
where ID_Produto Not IN (Select ID_Produto from tbl_produtos_parceiros)
order by NomeProduto
Results are as expected.
In the same form I have a search function. I tried the same condition, NOT IN
:
SELECT *
FROM tbl_produtos
WHERE id_produto LIKE '%ALH%'
OR nomeproduto LIKE '%ALH%'
OR responsavel LIKE '%ALH%'
OR precovenda LIKE '%ALH%'
AND id_produto NOT IN (SELECT id_produto
FROM tbl_produtos_parceiros);
Still brings the product "Alho", which is on the tbl_produtos_parceiros.
Upvotes: 0
Views: 124
Reputation: 1269613
If this is MS Access, you need to fix your wildcards and string delimiters as well as fix the syntax. I would also recommend NOT EXISTS
:
SELECT p.*
FROM tbl_produtos as p
WHERE (id_produto LIKE "*ALH*" OR
nomeproduto LIKE "*ALH*" OR
responsavel LIKE "*ALH*" OR
precovenda LIKE "*ALH*"
) AND
NOT EXISTS (SELECT 1
FROM tbl_produtos_parceiros as pp
WHERE pp.id_produto = p.id_produto
);
Upvotes: 1
Reputation: 222432
You need parentheses around the OR
ed conditions:
SELECT *
FROM tbl_produtos
WHERE
(
id_produto LIKE '%ALH%'
OR nomeproduto LIKE '%ALH%'
OR responsavel LIKE '%ALH%'
OR precovenda LIKE '%ALH%'
)
AND id_produto NOT IN (SELECT id_produto FROM tbl_produtos_parceiros);
Why you need this is because OR
has lower logical precedence than AND
. Without the parentheses, your query is equivalent to:
SELECT *
FROM tbl_produtos
WHERE
id_produto LIKE '%ALH%'
OR nomeproduto LIKE '%ALH%'
OR responsavel LIKE '%ALH%'
OR (
precovenda LIKE '%ALH%'
AND id_produto NOT IN (SELECT id_produto FROM tbl_produtos_parceiros)
);
Upvotes: 2