[英]Basic SQL sub-query
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 提前致谢
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%"
)
You don't need an additional join. 您不需要其他联接。 Just add the condition to the
where
clause with appropriate parentheses: 只需将条件添加到带有适当括号的
where
子句中:
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. 我认为这里的限制是适当的,尽管我不确定问题的意图是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.