select 表关系
select tables relationship
我需要帮助。我有 3 个这样的 table:
product
* id
- name
supplier
* id
- name
- active
product_supplier
* id_product
* id_supplier
最后table向供应商列出产品。
我需要的是建立一个查询,returns 我只有活跃的供应商,但仍然与特定产品无关。
谢谢!!
用子查询试试这个:
SELECT *
FROM supplier
WHERE active = 'Y'
AND id NOT IN (SELECT DISTINCT id_supplier
FROM product_supplier)
这是你的问题:"What I need is to build a query that returns me only active suppliers and still are not related to specific product."
您正在寻找没有特定产品的活跃供应商。
select s.id
from product_supplier ps join
supplier s
on ps.id_supplier = s.id
where s.active = 1
group by s.id
having sum(case when ps.id_product = XX then 1 else 0 end) > 0;
您也可以使用 not exists
:
select s.id
from supplier s
where s.active = 1 and
not exists (select 1
from product_supplier ps
where ps.id_supplier = s.id and
ps.id_product = XX
)
而且,您可以使用 left join
:
select s.*
from supplier s left join
product_supplier ps
on ps.id_supplier = s.id and ps.id_product = XX
where s.active = 1 and ps.id_supplier is null;
这似乎是 SQL 中最自然的表达方式。
非常感谢...它适用于此。
SELECT *
FROM supplier s
WHERE NOT
EXISTS (
SELECT *
FROM product_supplier ps
WHERE s.id = ps.id_supplier
AND ps.id_product =5
)
AND s.active =1
我需要帮助。我有 3 个这样的 table:
product
* id
- name
supplier
* id
- name
- active
product_supplier
* id_product
* id_supplier
最后table向供应商列出产品。
我需要的是建立一个查询,returns 我只有活跃的供应商,但仍然与特定产品无关。
谢谢!!
用子查询试试这个:
SELECT *
FROM supplier
WHERE active = 'Y'
AND id NOT IN (SELECT DISTINCT id_supplier
FROM product_supplier)
这是你的问题:"What I need is to build a query that returns me only active suppliers and still are not related to specific product."
您正在寻找没有特定产品的活跃供应商。
select s.id
from product_supplier ps join
supplier s
on ps.id_supplier = s.id
where s.active = 1
group by s.id
having sum(case when ps.id_product = XX then 1 else 0 end) > 0;
您也可以使用 not exists
:
select s.id
from supplier s
where s.active = 1 and
not exists (select 1
from product_supplier ps
where ps.id_supplier = s.id and
ps.id_product = XX
)
而且,您可以使用 left join
:
select s.*
from supplier s left join
product_supplier ps
on ps.id_supplier = s.id and ps.id_product = XX
where s.active = 1 and ps.id_supplier is null;
这似乎是 SQL 中最自然的表达方式。
非常感谢...它适用于此。
SELECT *
FROM supplier s
WHERE NOT
EXISTS (
SELECT *
FROM product_supplier ps
WHERE s.id = ps.id_supplier
AND ps.id_product =5
)
AND s.active =1