选择字段与多个预定义值相关联的行

时间:2018-12-05 20:11:49

标签: sql sql-server

我很难为这个问题选择标题。我不确定它能准确地描述我想要的内容,因此,如果您能帮助改善标题,而不是落选,我将不胜感激。 :)

我有以下(示例)表:

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.com1表中的USERS关联。但是,由于它没有与USERS中的任何其他ID关联,因此它不在结果中。我该如何实现?

3 个答案:

答案 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;

Demo

答案 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