SQL等于表达式

时间:2014-04-25 13:51:46

标签: mysql sql

我可以这样做吗

select * 
from tableA JOIN 
tableB ON tableA.id=tableB.id 
where tableB.someId = select id from otherTable where anotherId = 1

我有2个,可能吗?

3 个答案:

答案 0 :(得分:6)

当子查询只返回1个值时,可以使用=

当子查询返回的值超过1时,您必须使用INEXISTS

  1. 使用IN

    select * 
    from tableA JOIN 
    tableB ON tableA.id=tableB.id 
    where tableB.someId IN (select id 
                        from otherTable 
                        where anotherId = 1)
    

    IN确定指定的值是否与子查询或列表中的任何值匹配。

    了解更多here

  2. 使用EXISTS

    select * 
    from tableA JOIN 
    tableB ON tableA.id = tableB.id 
    where EXISTS (select id 
          from otherTable 
          where anotherId = 1
          and tableB.someId = otherTable .id)
    

答案 1 :(得分:1)

您可以使用IN Clause

select * 
from tableA JOIN 
tableB ON tableA.id = tableB.id 
where tableB.someId IN (select id 
                        from otherTable
                        where anotherId = 1)

您也可以使用EXISTS Condition

select * 
from tableA JOIN 
tableB ON tableA.id = tableB.id 
where EXISTS (select id 
              from otherTable ot
              where anotherId = 1
              and tableB.someId = ot.id)
如果子查询返回单个值,

=也可以正常工作。

Difference between EXISTS and IN

答案 2 :(得分:0)

select * 
from tableA 
JOIN tableB ON tableA.id=tableB.id 
join otherTable ON tableb.id = othertable.id 
where otherTable.anotherId = 1