简体   繁体   English

我们如何在mysql中实现交集和并集?

[英]How do we implement intersection and union in mysql?

So i am trying to Find the sids of suppliers who supply a red part and a green part. 因此,我试图查找提供红色部分和绿色部分的供应商的sid。

Here is SQL query 这是SQL查询

SELECT DISTINCT C.sid
FROM Catalog C, Parts P
WHERE C.pid = P.pid AND P.color  = 'red'
INTERSECT 
(   SELECT DISTINCT C.sid
    FROM Catalog C1,Parts P1
    WHERE C1.pid = P1.pid AND P1.color = 'green'
);

but i have a hard time implementing it in mysql , any suggestions appreciated 但我很难在mysql中实现它,任何建议表示赞赏

Just use two derived tables: 只需使用两个派生表:

 select
    t1.sid
    from
    (SELECT DISTINCT C.sid FROM Catalog C, Parts P WHERE C.pid = P.pid AND P.color = 'red') t1
    inner join
    (SELECT DISTINCT C.sid FROM Catalog C,Parts P WHERE C.pid = P.pid AND P.color = 'green') T2
    on t1.sid = t2.sid

(I just threw this together but it should at least be close) (我将其放在一起,但至少应该接近)

Why to go for such complex? 为什么要去这么复杂? Try this, may this work for your need 尝试一下,可能适合您的需要

SELECT DISTINCT C.sid
FROM Catalog C, Parts P
WHERE C.pid = P.pid AND P.color  = 'red' AND P.color = 'green'

This will give you join both the tables and will SELECT rows where color is either red and green . 这将使您同时join两个表并SELECT颜色为红色绿色的行 Kind of intersect operation, which you wish to apply. 您希望应用的一种相交操作。

As far as concept is concerned, I would suggest ( or what I know ) UNION and INTERSECTION should be applied when dealing with different tables. 就概念而言,我建议( 或我所知道的 )在处理不同表时应应用UNIONINTERSECTION It should not be practiced for operation over the same table. 不应将其实践用于在同一表上进行操作。

Suppose you have two tables A and B , then you can should apply UNION and INTERSECTION not on the same table. 假设您有两个表AB ,则可以将UNIONINTERSECTION应用于不同的表。 That is, If you are querying the same table A , and over same column then you can go for AND or OR operators. 也就是说,如果您要查询相同的表A ,并且查询的是同一列,则可以使用ANDOR运算符。

Making a note of the above, you can achieve this by doing AND . 记录以上内容,可以通过执行AND来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM