问题
I've got a table called products. Basically I need to search using the same word within various fields like this which works fine.
SELECT
`id`,
`product-id`,
`country`,
`name`,
`description`,
`branch`,
`stock`,
`price`
FROM
`products`
WHERE
`name` LIKE "%car%"
OR `description` LIKE "%car%"
OR `branch` LIKE "%car%"
OR `product-id` LIKE "%car%"
The problem is that now I want a different query. I'd like to show all the cars from an specific country only, plus the additional fields. So if I run this query
SELECT
DISTINCT(b.`id`) id,
a.id,
a.`product-id`,
a.`country`,
a.`name`,
a.`description`,
a.`branch`,
a.`stock`,
a.`price`
FROM
`products` as a,
(
SELECT
*
FROM
`products`
WHERE
`country` = "Canada"
LIMIT 0,
10
)AS b
WHERE
a.`id` = b.`id`
OR b.`product-id` LIKE "%car%"
OR b.`name` LIKE "%car%"
OR b.`branch` LIKE "%car%"
OR b.`description` LIKE "%car%"
LIMIT 0, 10
I get results from more than one country, what am I doing wrong?
Thanks in advance
回答1:
you just need to group your conditions,
SELECT ...
FROM ...
WHERE (a.`id` = b.`id`) AND
(
b.`product-id` LIKE "%car%" OR
b.`name` LIKE "%car%" OR
b.`branch` LIKE "%car%" OR
b.`description` LIKE "%car%"
)
回答2:
You don't need an additional join. Just add the condition to the where
clause with appropriate parentheses:
SELECT
`id`,
`product-id`,
`country`,
`name`,
`description`,
`branch`,
`stock`,
`price`
FROM
`products`
WHERE
country = 'Canada' and
( `name` LIKE "%car%"
OR `description` LIKE "%car%"
OR `branch` LIKE "%car%"
OR `product-id` LIKE "%car%"
)
limit 30
I think the limit is appropriate here, although I'm not sure what the intention is in the question.
来源:https://stackoverflow.com/questions/14824780/basic-sql-sub-query