Basic SQL sub-query

谁都会走 提交于 2020-01-02 10:04:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!