MYSQL SELECT WHERE CLAUSE-排除行

时间:2019-02-13 13:37:19

标签: mysql sql

在MYSQL中,假设我有以下两个表。

“订单”:

id   |    name    | customer_id |    type   |  id_fabric
--------------------------------------------------------
1    | "P1601"    |      0      |     1     |    1    
2    | "M6451"    |      0      |     2     |    2    
3    | "T8200"    |      8      |     1     |    1    
4    | "R7441"    |      0      |     2     |    2    
5    | "S8018"    |      2      |     1     |    3    
6    | "P1240"    |      7      |     1     |    3    

“面料”:

id    |  color  |  remaining 
----------------------------
1     | black   |  3.40 
2     | red     |  16 
3     | navy    |  12 

我想创建一个查询以仅检索剩余大于5的面料,这些面料没有customer_id = 0的任何订单,并且订单类型不等于2

所以在这种情况下,结果将是:

id  | color   |  remaining
------------------------------------------------
3   | navy    |  12

我试图通过使用下面的Sql查询来实现这一点,但是没有得到预期的结果:

SELECT
    color,
    remaining
FROM
    fabrics
LEFT JOIN orders ON id_fabric = id
WHERE
    remaining > 2 AND id IN(
    SELECT
        id_fabric
    FROM
        orders
    WHERE
        type != 2 AND customer_id != 0
)
GROUP BY
    id

有什么想法吗?

5 个答案:

答案 0 :(得分:2)

使用NOT EXISTS

SELECT
    f.color,
    f.remaining
FROM fabrics f
WHERE f.remaining > 5 AND 
    NOT EXISTS(
        SELECT 1
        FROM orders o
        WHERE o.id_fabric = f.id AND
              o.type = 2 AND o.customer_id = 0
    )

请注意,原始查询中也可以省略JOIN和GROUP BY。

答案 1 :(得分:0)

尝试如下

SELECT
    color,
    remaining
FROM
    fabrics
 JOIN orders ON id_fabric = id
where customer_id!=0 and remaining>5 and type!=2

答案 2 :(得分:0)

使用JOINWHERE条件和'GROUP BY`

id在两个表中都相同,因此请使用表的别名。

select f.id,f.color,f.remaining
from fabrics f
join orders o on o.id_fabric  = f.id
where f.remaining > 2 and o.type !=2 and o.customer_id!=0
group by f.id

答案 3 :(得分:0)

在这种情况下,我认为在需要条件的地方不要选择subselect。 您可以像

一样继续
SELECT
    color,
    remaining
FROM
    fabrics
LEFT JOIN orders ON id_fabric = id
WHERE
    remaining > 2  
    AND customer_id!=0
    AND type != 0
GROUP BY
    id 

答案 4 :(得分:0)

您可以尝试使用相关子查询

SELECT
    color,
    remaining
FROM
    fabrics
LEFT JOIN orders ON id_fabric = id where remaining > 5 and 
not exists (select 1 from orders o where o.id_fabric=fabrics.id and o.customer_id=0 and o.type=2)