sql查询链接两个表

时间:2012-05-17 07:01:56

标签: sql asp-classic vbscript sql-server-2000

我有一个名为users的表,其中存储了员工数据。 此外,我还有另一张表payment_details,其中存储了员工的付款相关数据 这两个表如下。

此表格为用户

sr_no  emp_no  username  payment

1     1001      leroy    <null>
2     1003      harry    <null>
3     1004      Tom      <null>   
4     1008      Jon      <null>    

下表为 payment_details

    sr_no       name     number      month    status        date
      43        Jon       1008       January  paid         5/16/2012
      44        Jon       1008       January  balance      5/16/2012
      45        Harry     1003       January  paid         5/16/2012
      46        Tom       1004       January  paid         5/16/2012
      47        leroy     1001       January  paid         5/16/2012
      48        Jon       1008       January  paid         5/16/2012
      49        Harry     1003       January  paid         5/16/2012
      50        Jon       1008       February balance      5/16/2012
      51        leroy     1001       February paid         5/16/2012
      52        Jon       1008       February paid         5/16/2012
      53        Tom       1004       February balance      5/16/2012

我的问题是,当他/她的状态支付 payment_details时,将“用户”表付款列更新为“已付款”

3 个答案:

答案 0 :(得分:3)

您可以这样做:http://www.sqlfiddle.com/#!3/db13f/18

update users set payment = 'paid'
from
(
  select number
  from payment_details
  group by number
  having sum(case when status = 'paid' then 1 end) 
       = count(*)
) as x
where x.number = users.emp_no;

或者:http://www.sqlfiddle.com/#!3/db13f/19

update users
  set payment = x.upd
from 
(
  select u.emp_no, 

      case when sum(case when d.status = 'paid' then 1 end)  = count(*) then
         'paid'
      else
         null
      end as upd

  from users u

  left join payment_details d
  on d.number = u.emp_no

  group by u.emp_no
) as x
where x.emp_no = users.emp_no;

它们的不同之处在于它更新了多少行。在第二个查询中,它会更新所有用户,无论用户是否具有全部付费状态('paid')(null);在第一个查询中,它仅更新已付款的人。

第二个查询的优势在于,当您将给定用户的'paid'上的所有status payment_detail中的一个更改为“未付费”时,它可以还原用户的payment状态为null

答案 1 :(得分:1)

UPDATE order_details
SET payment= 'paid'
WHERE not EXISTS (SELECT 1
              FROM payment_details 
              WHERE payment_details.emp_no= order_details.emp_no
              AND   payment_details.status <> 'paid'
             )

答案 2 :(得分:0)

还有一种简单的方法可以将particulars表的值变为变量并更新tabe,如下所示:

declare @bb varchar(50)
select @bb= status from payment_details where name=@name and id=@id
update uuser set payment = @bb
where name = @name and id=@id