[英]How to GROUP multiple records from two different SQL statements
I have a table called tbl which contains all the data I need. 我有一个名为tbl的表,其中包含我需要的所有数据。 I have many columns in this table, but for purposes of this example I will only list the columns necessary to accomplish this task.
该表中有许多列,但是出于本示例的目的,我将仅列出完成此任务所需的列。
Here's how data stored in the tbl (note uID is char(20) and cID is int)*: 这是在tbl中存储数据的方式(注意 uID是char(20),cID是int)*:
uID cID
uID cID
1 10
1 10
1 11
1 11
1 12
1 12
2 11
2 11
We usually query this table like 我们通常像这样查询该表
SELECT * FROM tbl WHERE uID = "1"
So it returns 所以它返回
uID cID
uID cID
1 10
1 10
1 11
1 11
1 12
1 12
But I also need to return the row where uID is different but cID do match. 但是我还需要返回uID不同但cID匹配的行。 Or grab the uID of the second row (which is 2) based on cID and do a select statement like this:
或者,根据cID获取第二行的uID(即2),然后执行以下select语句:
SELECT * FROM tbl WHERE uID in ('1','2')
That query will return what I'm looking for 该查询将返回我要查找的内容
uID cID
uID cID
1 10
1 10
1 11
1 11
1 12
1 12
2 11
2 11
This table contains a lot of rows and I want to be able to do this programatically for every call where cID matches and uID is different. 该表包含很多行,我希望能够以编程方式针对cID匹配且uID不同的每个调用执行此操作。
Any suggestions? 有什么建议么?
I think this may be what you want: 我认为这可能是您想要的:
SELECT *
FROM tbl
WHERE uID = '1'
UNION ALL
SELECT *
FROM tbl
WHERE uID <> '1' AND
EXISTS (select 1 from tbl tbl2 where tbl2.uId = '1' and tbl2.cID = tbl.cID);
or something like this: 或类似这样的东西:
SELECT uID, cID
FROM tbl
WHERE uID IN
(
SELECT uID
FROM tbl
INNER JOIN
(
SELECT cID
FROM tbl
GROUP BY cID
HAVING count(*) > 1
) c ON c.cID = tbl.cID
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.