[英]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
andINTERSECTION
should be applied when dealing with different tables. 就概念而言,我建议( 或我所知道的 )在处理不同表时应应用UNION
和INTERSECTION
。 It should not be practiced for operation over the same table. 不应将其实践用于在同一表上进行操作。Suppose you have two tables
A
andB
, then you can should applyUNION
andINTERSECTION
not on the same table. 假设您有两个表A
和B
,则可以将UNION
和INTERSECTION
应用于不同的表。 That is, If you are querying the same tableA
, and over same column then you can go forAND
orOR
operators. 也就是说,如果您要查询相同的表A
,并且查询的是同一列,则可以使用AND
或OR
运算符。
Making a note of the above, you can achieve this by doing AND
. 记录以上内容,可以通过执行AND
来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.