带有两个链接表的SQL查询

时间:2017-08-17 06:21:54

标签: sql join sql-server-2012 inner-join

请帮助撰写此查询。这是表格图表:

diagram

用户回应销售特定销售类型的药品。如何查找针对特定用户ID响应相同销售类型的相同药物的用户?

例如:

  • Alice回应销售零售
  • 中的维生素A,维生素B
  • Bob回应在零售州市场
  • 销售维生素A,维生素B
  • 查理在州市场回应维生素B,维生素C

响应相同salestype-drugs的用户

  • for Alice is Bob
  • for Bob是Alice和Charlie
  • 查理是鲍勃

1 个答案:

答案 0 :(得分:2)

对于给定示例:

对于用户通过所有销售类型销售相同药物的示例数据:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>


<div id="container">
<div class="row">
  <div class="col-xs-6 col-sm-6">
    <img src="https://placehold.it/360x360">
  </div>
  <div class="col-xs-6 col-sm-6">
    <h1>First person's name</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque id ex ut nunc pharetra congue. Morbi ut lectus vulputate nunc congue convallis. Nunc ultricies quam ac dolor tincidunt feugiat. Integer condimentum metus leo, a interdum felis molestie in. Ut non diam non ligula aliquam iaculis vestibulum quis urna. Maecenas efficitur purus et elementum auctor. Praesent condimentum id sapien vitae tempor. Ut ultrices accumsan lectus, quis ullamcorper velit auctor at. Suspendisse bibendum, odio gravida rhoncus pretium, enim elit porta massa, quis sagittis dolor sapien vel nulla. Nullam et enim ac tellus aliquam pulvinar. Proin et bibendum dui.
    </p>
  </div>
</div>
<div class="row">
  <div class="col-xs-6 col-sm-6">
    <img src="https://placehold.it/360x360">
  </div>
  <div class="col-xs-6 col-sm-6">
      <h1>Second person's name</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque id ex ut nunc pharetra congue. Morbi ut lectus vulputate nunc congue convallis. Nunc ultricies quam ac dolor tincidunt feugiat. Integer condimentum metus leo, a interdum felis molestie in. Ut non diam non ligula aliquam iaculis vestibulum quis urna. Maecenas efficitur purus et elementum auctor. Praesent condimentum id sapien vitae tempor. Ut ultrices accumsan lectus, quis ullamcorper velit auctor at. Suspendisse bibendum, odio gravida rhoncus pretium, enim elit porta massa, quis sagittis dolor sapien vel nulla. Nullam et enim ac tellus aliquam pulvinar. Proin et bibendum dui.
    </p>
  </div>
</div>

更灵活的数据:

如果您想支持按销售额X销售药品A且按销售Y销售药品B(但销售Y不销售药品A或销售X销售药品B)的用户,则可以使用此数据模型:

SELECT mus.userId 
FROM User2SalesType qus 
INNER JOIN User2Drug qud       ON qus.UserId = qud.UserId
INNER JOIN User2SalesType mus  ON qus.SalesTypeId = mus.SalesTypeId
                               AND mus.UserId != qus.UserId
INNER JOIN User2Drug mud       ON qud.DrugId = mud.DrugId 
                               AND mus.UserId = mud.UserId
WHERE qus.UserId = ? # querying user ID

然后您可以通过自我加入的方式查询响应:

User:       id, etc.
Response:   userId, salesTypeId, drugId
SalesType:  id, etc.
Drug:       id, etc.