Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何编写具有两种状态的查询?_Sql_Sqlite_Join - Fatal编程技术网

Sql 如何编写具有两种状态的查询?

Sql 如何编写具有两种状态的查询?,sql,sqlite,join,Sql,Sqlite,Join,我有一位顾客: Id Code Name 1 100 John 2 200 Jack 3 300 Mike 4 400 Betty Id Code Name 1 1000 cash 2 2000 cheque 3 3000 free Id Code Name 1 1000 cash 2 2000 cheque 3 3000 free 和表SaleType: I

我有一位顾客:

Id  Code    Name
1   100     John
2   200     Jack
3   300     Mike
4   400     Betty
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
和表SaleType

Id  Code    Name
1   100     John
2   200     Jack
3   300     Mike
4   400     Betty
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
以及一个表,该表描述了哪个客户的销售类型为SaleType\u customer

Id  SaleTypeID  CustomerID
1   1           1
2   1           2
3   2           1
4   2           3
我想写一个查询,它获取客户的销售类型。但是,如果客户不在表SaleType\u customer中,查询将返回所有SaleTypes。如何编写此查询

我的问题是:

SELECT  SaleType.ID, SaleType.Code, SaleType.Name
 FROM SaleType left outer join SaleType_Customer on SaleType.Id = SaleType_Customer.SaleTypeID 

Where SaleType_Customer.CustomerID= 1 
我想要John(id=1)的结果:

对于Betty(id=4)来说,这是完整的,因为她不在SaleType\u客户中:

Id  Code    Name
1   100     John
2   200     Jack
3   300     Mike
4   400     Betty
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
Id  Code    Name
1   1000    cash
2   2000    cheque
3   3000    free
我应该如何编写查询

SELECT SaleType.ID, SaleType.Code, SaleType.Name
  FROM SaleType
 WHERE NOT EXISTS (SELECT *
          FROM SaleType_Customer
         WHERE SaleType_Customer.Customerid = 4)
UNION

SELECT SaleType.ID, SaleType.Code, SaleType.Name
  FROM SaleType
 INNER JOIN SaleType_Customer
    ON SaleType_Customer.Saletypeid = SaleType.Id
 WHERE SaleType_Customer.Customerid = 4


以下是两种说法都是正确的。哪一个更快?似乎@snyder答案更快,因为执行计划。我必须承认,这也更具创新性。谢谢你的回答。这两个都是真的。哪一个更快?