MYSQL SELECT WHERE子句-排除行
在MYSQL中,假设我有以下两个表 “命令”: “织物”: 我想创建一个查询,仅检索剩余大于5的结构,这些结构没有任何MYSQL SELECT WHERE子句-排除行,mysql,sql,Mysql,Sql,在MYSQL中,假设我有以下两个表 “命令”: “织物”: 我想创建一个查询,仅检索剩余大于5的结构,这些结构没有任何customer\u id=0的订单,并且其订单类型不等于2 因此,在这种情况下,结果将是: id | color | remaining ------------------------------------------------ 3 | navy | 12 我尝试使用以下Sql查询来实现这一点,但没有得到预期的结果: SELECT color
customer\u 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
有什么想法吗?使用
不存在
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和groupby。尝试下面的方法
SELECT
color,
remaining
FROM
fabrics
JOIN orders ON id_fabric = id
where customer_id!=0 and remaining>5 and type!=2
使用
JOIN
和WHERE
条件和“分组依据”`
id
在两个表中都是相同的字段,因此请为表使用alies名称
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
我认为在这种情况下,在你的where条件中的子选择是不必要的。 你可以像这样继续下去
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
您可以尝试使用相关子查询
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)
不知道为什么PHP标签在这里。这很可能只是Mysql问题。请更新答案以修复语法错误。子查询条件中缺少
和
,以及id中删除id
不存在
我解释了一个稍微不同的问题,我认为最后一个条件应该是和(o.type=2或o.customer\u id=0)
,但决定哪一个是OPone@JuanCarlosOropeza我也这么做了,然而,OP明确指出了和其
,并没有限定在示例中包括/排除这些订单的条件。客户id=0且其订单类型不等于2因为订单似乎是多(订单)对一(结构)关系,而不是一对一关系,这将根据符合条件的结构的订单数量生成同一结构的多行。为确保预期结果,您应该将订单表的条件从的WHERE
移动到的JOIN ON
。类似于o.id_fabric=f.id和o.customer_id!=0和o.type!=2此外,在使用时,您需要指定任意值()
或聚合函数,以避免MySQL 5.7+仅\u FULL\u GROUP\u BY
错误。
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
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)