#26 包含JOIN遗忘的行

来源:互联网 发布:mac电脑中病毒怎么杀毒 编辑:程序博客网 时间:2024/06/06 22:27
  1. --包含JOIN遗忘的行
  2. select getdate() --2009-01-05 22:54:33.763 in 西安 by 陈亮
  3. /*--生成数据
  4. use tempdb
  5. IF object_id('customer') is not NULL
  6.     drop table customer
  7. Go
  8. Create table customer (id int ,name varchar(20))
  9. Go
  10. insert into customer
  11. select 1,'Bety' UNION ALL
  12. select 2,'Robert' UNION ALL
  13. select 3,'Janette'
  14. --
  15. IF object_id('invoice') is not NULL
  16.     drop table invoice
  17. Go
  18. Create table invoice (id int ,whn datetime,Custid int ,cost int)
  19. Go
  20. insert into invoice
  21. select 1,'2009-01-01',1,100 UNION ALL
  22. select 2,'2009-01-02',1,500 UNION ALL
  23. select 3,'2009-01-05',3,200
  24. --*/
  25. --默认情况下,JOIN就是INNER JOIN。 它将仅仅给出同时匹配两个表的数据行:
  26. select *
  27.     from customer INNER JOIN invoice
  28.         on (customer.id=custid);
  29. /*
  30. id    name    id    whn    Custid    cost
  31. 1    Bety    1    2009-01-01 00:00:00.000    1    100
  32. 1    Bety    2    2009-01-02 00:00:00.000    1    500
  33. 3    Janette    3    2009-01-05 00:00:00.000    3    200
  34. */
  35. --与此相反,LEFT OUTER JOIN 将包括左表中的所有行——即使有的行不匹配右侧表的任意行业是如此:
  36. select *
  37.     from customer LEFT OUTER JOIN invoice
  38.         on (customer.id=custid);
  39. /*
  40. id    name    id    whn    Custid    cost
  41. 1    Bety    1    2009-01-01 00:00:00.000    1    100
  42. 1    Bety    2    2009-01-02 00:00:00.000    1    500
  43. 2    Robert    NULL    NULL    NULL    NULL
  44. 3    Janette    3    2009-01-05 00:00:00.000    3    200
  45. */
  46. --能够使用短语LEFT JOIN 取代 LEFT OUTER JOIN 。单词OUTER是个可选词汇。
  47. --类似地,如果你在使用内连接,那么可以通过使用INNER JOIN 来取代JOIN 来明确说明连接类型。这点要求在Access中是强制性的。
  48. --过滤必须在连接条件(ON子句)中完成。在SQL中,首先执行JOIN子句,然后应用WHERE条件。
  49. --如果想得到Robbert的数量0,那么需要使用LEFT OUTER JOIN ,这样,左表(customer)的每一行都出现在结果中:
  50. select [name] ,count(custid)
  51.     from customer LEFT JOIN invoice on (customer.id=custid)
  52. group by name
  53. /*
  54. name    count(custid)
  55. Bety    2
  56. Janette    1
  57. Robert    0
  58. */
  59. --注意
  60. select [name] ,count(*)
  61.     from customer LEFT JOIN invoice on (customer.id=custid)
  62. group by name
  63. /*
  64. name    count(*)
  65. Bety    2
  66. Janette    1
  67. Robert    1
  68. */
  69. select [name] ,count(name)
  70.     from customer LEFT JOIN invoice on (customer.id=custid)
  71. group by name
  72. /*
  73. name    count(name)
  74. Bety    2
  75. Janette    1
  76. Robert    1
  77. */
  78. --使用UNION也可以解决问题,编写第二个查询,它对不在invoice中的客户返回0:
  79. select [name] ,count(*)
  80.     from customer JOIN invoice on (customer.id=custid)
  81. group by name
  82. UNION
  83. select name ,0
  84.     from customer a
  85. where not exists (select * from invoice b where b.custid=a.id)
  1. --END*/

 

原创粉丝点击