简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM