简体   繁体   English

从多个表查询中选择

[英]Select from many to many table query

I have some tables: 我有一些表:

Sessions 会议
SessionID int PK SessionID int PK
Created datetime 创建日期时间
SiteId int FK SiteId int FK

Tracking_Parameters Tracking_Parameters
ParamID int PK ParamID int PK
ParamName nvarchar ParamName nvarchar

Session_Custom_Tracking Session_Custom_Tracking
SessionID int FK SessionID int FK
ParamID int FK ParamID int FK
ParamValue nvarchar ParamValue nvarchar

Site_Custom_Parameters Site_Custom_Parameters
SiteID int FK SiteID int FK
ParamID int FK ParamID int FK
ParamKey nvarchar ParamKey nvarchar

Sessions : Contains the unique session id for a visitor and the time they entered the site. 会话 :包含访问者的唯一会话ID以及他们进入网站的时间。

Tracking_Parameters : Contains a list of things that you may want to track on a site (ie Email Open, Email Click, Article Viewed, etc.) Tracking_Parameters :包含您可能想要在网站上跟踪的内容列表(即电子邮件打开,电子邮件点击,文章查看等)

Site_Custom_Parameters : For a particular site (table not shown), declares the key value for a Tracking_Parameter (ie the key to look for in a query string or route) Site_Custom_Parameters :对于特定站点(表未显示),声明Tracking_Parameter的键值(即在查询字符串或路径中查找的键)

Session_Custom_Tracking : The link between a session and a tracking parameter and also contains the value for the parameter's key when it was found by my application. Session_Custom_Tracking :会话和跟踪参数之间的链接,还包含我的应用程序找到参数时键的值。

Question: 题:

I want to select session id's where for these particular sessions, there is a record in the Session_Custom_Tracking for two different ParamID's. 我想选择会话ID,对于这些特定会话,Session_Custom_Tracking中有两个不同ParamID的记录。 I want to find sessions where a user both opened an email (paramid 1) and clicked (paramid 3) a link in that email. 我想找到一个用户同时打开电子邮件(paramid 1)并点击(paramid 3)该电子邮件中的链接的会话。

You can join to the same table twice: 您可以两次加入同一个表:

SELECT S.SessionID
FROM Sessions AS S
JOIN Session_Custom_Tracking AS SCT1
ON SCT1.SessionID = S.SessionID
AND SCT1.ParamID = 1
JOIN Session_Custom_Tracking AS SCT2
ON SCT2.SessionID = S.SessionID
AND SCT2.ParamID = 3

An alteranative that might be easier to read (because it more closely matches the way you describe the problem) is to use WHERE EXISTS : 一个可能更容易阅读的替代品(因为它更符合您描述问题的方式)是使用WHERE EXISTS

SELECT S.SessionID
FROM Sessions AS S
WHERE EXISTS
(
    SELECT *
    FROM Session_Custom_Tracking AS SCT1
    WHERE SCT1.SessionID = S.SessionID
    AND SCT1.ParamID = 1
)
AND EXISTS
(
    SELECT *
    FROM Session_Custom_Tracking AS SCT2
    WHERE SCT2.SessionID = S.SessionID
    AND SCT2.ParamID = 3
)

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

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