【问题标题】:mysql join two tablesmysql连接两个表
【发布时间】:2011-04-07 17:37:13
【问题描述】:

我在连接两个表时遇到问题:

table1    
id  name  
1   aaa  
2   bbb  
3   ccc  

table2    
id table1_id name  
1 1          x1  
2 1          x2  
3 2          s1 

table1 是主表,table2 包含属性。

我需要加入并搜索两个表,但显示的结果与第一个表不同。

使用JOIN 时,我从table2 获得多个结果。

场景是我需要在TABLE2中搜索主表TABLE1和ALL ATTRIBUTES,如果找到就返回

【问题讨论】:

  • "如果找到就返回",什么意思?您需要退回什么?

标签: sql mysql


【解决方案1】:
select distinct(name) from table1 inner join table2 on table1.id = table2.table1_id where table2.name = x2;

应该做的伎俩。

【讨论】:

    【解决方案2】:

    如果您需要两个表中都存在的条目:

     SELECT * from Table1 t1
     WHERE YourConditionsHere
     AND EXISTS (SELECT 1 from Table2 t2
                 WHERE t1.Id = t2.Table1_id 
                   AND YourConditionsHere)
    

    如果您需要 Table1 中不存在 Table2 中的条目的条目

     SELECT * from Table1 t1 
     LEFT JOIN 
     (SELECT * from Table2 
      WHERE YourConditionsHere
     ) t2
     ON (t1.Id = t2.Table1_id) 
     WHERE YourConditionsHereForTable1
    

    【讨论】:

    • 这仅显示匹配项,但我在 table1 中有一些行,而 table2 中没有属性
    • @user438755,我扩展了我的答案。
    【解决方案3】:

    另一种选择

    select * from table1 t1 where t1.id in (select table1_id from table2 t2 where t2.name = "x1");
    

    最好检查所有建议查询的查询平原(即EXPLAIN),并检查最适合您的具体情况的查询。

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 2014-11-07
      相关资源
      最近更新 更多