【问题标题】:SQL Conditional Join QuerySQL 条件连接查询
【发布时间】:2020-03-25 05:04:38
【问题描述】:

考虑 3 个表格:

表1

id(pkey) text 
col1  text

示例(表1)

id col1
1  value1
2  value2

表2

id(pkey) text 
name  text

示例(表2)

id name
1  name1
2  name2
3  name3

表3

table1_id text 
table2_id text

示例(表3)

table1_id table2_id
1          1
2          1
2          2

您如何使用联接从表 1 中选择条目(唯一),这样:

  1. Table1.id == Table3.table1_id
  2. Table2.id == Table3.table2_id
  3. 链接到该 table1 条目的所有 Table2.name 都与给定的字符串集完全匹配。

预期样本: 如果给定的搜索集是:['name1', 'name2'];返回 table1 中的所有条目,这些条目链接到 table3 中名称为“name1”或“name2”的所有条目。

在所考虑的示例中,示例有效响应:

id col1
2  value2 

【问题讨论】:

  • (1) 用您真正使用的数据库标记您的问题。 (2) 提供样本数据和期望的结果。
  • 嗨,EI Cid,我已经在 SQL Server 上检查了以下查询,它对我来说工作正常,如果仍有问题,请告诉我。
  • @GordonLinoff 处理了您的评论。
  • @AjeetVerma 您的查询看起来不正确。也许这个例子可能会有所帮助?

标签: mysql sql postgresql join


【解决方案1】:

如果我理解正确,你可以使用group byhaving

select t3.table1_id
from table3 t3 join
     table2 t2
     on t3.table2_id = t2.id
group by t3.table1_id
having sum( case when t2.name in (?, ?, ?) then 1 else 0 end) = count(*) and
       count(*) = 3;  -- number of elements 

注意:这假定table3 没有重复项,通常情况就是这样。

【讨论】:

    【解决方案2】:

    请使用下面的 SQL 查询来解决您的问题,我已经尝试过了,它对我有用。

    SELECT t1.id
        ,t1.col1
    FROM Table1 AS t1
    INNER JOIN Table3 AS t3 ON t1.id = t3.table1_id
    INNER JOIN Table2 AS t2 ON t2.id = t3.table2_id
    WHERE t2.name = t1.col1 
    

    请查看快照以了解此查询的结果以便更好地理解。

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多