我很难为这个问题选择标题。我不确定它能准确地描述我想要的内容,因此,如果您能帮助改善标题,而不是落选,我将不胜感激。 :)
我有以下(示例)表:
USERS:
+----------+
| id |
+----------+
| 1 |
------------
| 3 |
------------
| 4 |
+----------+
URLS:
+----------+----------+
| id | url |
+----------+----------+
| 1 | a.com |
-----------------------
| 1 | b.com |
-----------------------
| 1 | d.com |
-----------------------
| 2 | a.com |
-----------------------
| 2 | e.com |
-----------------------
| 3 | a.com |
-----------------------
| 3 | e.com |
-----------------------
| 3 | f.com |
-----------------------
| 3 | g.com |
-----------------------
| 4 | a.com |
-----------------------
| 4 | e.com |
+----------+----------+
我想从URLS
中选择与USERS
中至少两个id对应的所有URL。因此,对于示例,使用以下示例表进行查询的结果:
+----------+
| url |
+----------+
| a.com | <- associated with ids: 1, 3, 4
------------
| e.com | <- associated with ids: 3, 4
+----------+
如您所见,例如b.com
与1
表中的USERS
关联。但是,由于它没有与USERS
中的任何其他ID关联,因此它不在结果中。我该如何实现?
答案 0 :(得分:2)
如果最小值与每个url
的最大值不相等,则您将有多个与ids
关联的ID,我们可以通过执行以下操作将USERS
排除在inner join
表中select url
from URLS as a
inner join USERS as b
on a.id=b.id
group by url
having max(b.id)<>min(b.id)
,也许是这样的
select distinct city
from station
where substring(city,1,1) not in('A','E','I','O','U');
答案 1 :(得分:1)
您可以将EXISTS()
用作
SELECT Url
FROM Urls T
WHERE EXISTS(
SELECT 1
FROM Urls
WHERE ID != T.ID
AND
Url = T.Url
)
GROUP BY Url;
或
SELECT T1.Url
FROM Urls T1 JOIN Urls T2
ON T1.ID != T2.ID
AND T1.Url = T2.Url
GROUP BY T1.Url;
更新:
由于您需要与Users
表联接
SELECT T1.Url
FROM Urls T1 INNER JOIN Users T2
ON T1.ID = T2.ID
WHERE EXISTS(
SELECT 1
FROM Urls
WHERE ID != T1.ID
AND
Url = T1.Url
)
GROUP BY T1.Url;
SELECT T1.Url
FROM Urls T1 INNER JOIN Urls T2
ON T1.ID != T2.ID
AND T1.Url = T2.Url
INNER JOIN Users U ON T1.ID = U.ID
GROUP BY T1.Url;
答案 2 :(得分:0)
如果要在同一列中查看所有关联的ID,可以使用STUFF()
。这是您的示例:
--DROP TABLE Users;
CREATE TABLE Users
(
id INT
);
--DROP TABLE Urls;
CREATE TABLE Urls
(
id INT
,Url VARCHAR(100)
);
INSERT INTO Users VALUES(1),(2),(3),(4)
INSERT INTO URLs VALUES
(1,'a.com')
,(1,'b.com')
,(1,'d.com')
,(2,'a.com')
,(2,'e.com')
,(3,'a.com')
,(3,'e.com')
,(3,'f.com')
,(3,'g.com')
,(4,'a.com')
,(4,'e.com')
SELECT *,
STUFF((SELECT distinct ',' + CAST(ID AS VARCHAR)
from URLs U2
WHERE U1.Url=U2.Url
AND EXISTS (SELECT 1 FROM Users US WHERE U2.id=US.id)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
FROM
(SELECT DISTINCT Url FROM Urls) U1