Basic SQL sub-query

2019-05-23 16:39发布

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

2条回答
Viruses.
2楼-- · 2019-05-23 17:12

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.

查看更多
Evening l夕情丶
3楼-- · 2019-05-23 17:19

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%"
        )
查看更多
登录 后发表回答