我需要一些sql查询的帮助。我有两个表,计算机和产品由ComputerProduct连接。现在我想知道是否有任何具有相同名称的计算机具有相同的产品主名称和辅助名称。对以下数据运行查询将返回c1和c2。 如何避免表中的重复?
Computer
-----------------------
Id Name
c1 computer1
c2 computer1
c3 computer2
ComputerProduct
-----------------------
ComputerId ProductId
c1 p1
c1 p2
c2 p1
c2 p2
c3 p1
c3 p2
Product
-----------------------
Id Name Type
p1 A1 Primary
p2 a1010 Secondary
答案 0 :(得分:1)
我最近处理过同样的问题。
MySQL能够制作不接受重复的表格。
您可以更改表格,以删除重复的值。
ALTER TABLE ComputerProduct
ADD UNIQUE (ComputerID);
重要提示:在使用之前重复使用您的表,这样您就不会冒任何数据丢失......
一切顺利,祝你好运, CrypticPug
答案 1 :(得分:1)
with dat
as (select c.id,c.name, p.prodtype,p.prodname
from computer c join computerProduct cp on c.id = cp.computerId
join product p on cp.productId = p.id)
select * from computer
where name in
(
select name from (select id,name,prodname from dat where prodtype='Primary')x
group by name
having count(*)>1
intersect
select name from (select id,name,prodname from dat where prodtype='Secondary')x
group by name
having count(*)>1
)
答案 2 :(得分:0)
我试过(在MSSQL上)一个如下的查询(可能它可以简化......)。
在内部查询中,使用两个连接来提取所有组合,用于'主要'和'中学'类型。
然后使用computer.name和product的名称对记录进行分组和计数。
有'有COUNT(*)> 1'仅提取所需的记录,即具有相同的计算机名称和产品名称。
最后,只提取与提取的computer.name(s)和产品名称对应的ID。
SELECT X.ID
FROM COMPUTER X
INNER JOIN COMPUTERPRODUCT Y1 ON X.ID=Y1.COMPUTERID
INNER JOIN COMPUTERPRODUCT Y2 ON X.ID=Y2.COMPUTERID
INNER JOIN PRODUCT Z1 ON Y1.PRODUCTID = Z1.ID AND Z1.[TYPE] ='Primary'
INNER JOIN PRODUCT Z2 ON Y2.PRODUCTID = Z2.ID AND Z2.[TYPE] ='Secondary'
WHERE EXISTS (SELECT 1
FROM (SELECT A.NAME, C1.NAME AS C1_NAME, C2.NAME AS C2_NAME, COUNT(*) AS RC
FROM COMPUTER A
INNER JOIN COMPUTERPRODUCT B1 ON A.ID=B1.COMPUTERID
INNER JOIN COMPUTERPRODUCT B2 ON A.ID=B2.COMPUTERID
INNER JOIN PRODUCT C1 ON B1.PRODUCTID = C1.ID AND C1.[TYPE]='Primary'
INNER JOIN PRODUCT C2 ON B2.PRODUCTID = C2.ID AND C2.[TYPE]='Secondary'
GROUP BY A.NAME, C1.NAME, C2.NAME
HAVING COUNT(*) >1
) E WHERE X.NAME = E.NAME AND Z1.NAME =C1_NAME AND Z2.NAME =C2_NAME);
示例数据:
INSERT INTO COMPUTER VALUES ('c1','computer1');
INSERT INTO COMPUTER VALUES ('c2','computer1');
INSERT INTO COMPUTER VALUES ('c3','computer3');
INSERT INTO COMPUTER VALUES ('c4','computer1');
INSERT INTO COMPUTERPRODUCT VALUES ('c1','p1');
INSERT INTO COMPUTERPRODUCT VALUES ('c1','p2');
INSERT INTO COMPUTERPRODUCT VALUES ('c2','p1');
INSERT INTO COMPUTERPRODUCT VALUES ('c2','p2');
INSERT INTO COMPUTERPRODUCT VALUES ('c3','p1');
INSERT INTO COMPUTERPRODUCT VALUES ('c3','p2');
INSERT INTO COMPUTERPRODUCT VALUES ('c4','p1');
INSERT INTO COMPUTERPRODUCT VALUES ('c4','p3');
INSERT INTO PRODUCT VALUES ('p1','A1','Primary');
INSERT INTO PRODUCT VALUES ('p2','a1010','Secondary');
INSERT INTO PRODUCT VALUES ('p3','b2020','Secondary');
输出:
ID
c1
c2