难以解决联合查询

时间:2013-05-12 05:38:13

标签: ms-access

我有两张桌子:

S_tbl

====================
id | barcode | qty |
====================
1 | 1234     | 10  |
1 | 111      | 5   |
1 | 1234     | 10  |

K_tbl

=============================
id | barcode | qty | newQty |
=============================
1  | 1234    | 10  | 20     |

我运行此查询:

SELECT K_Tbl.id, K_Tbl.barcode, K_Tbl.Qty, K_Tbl.NewQty
FROM   K_Tbl where K_Tbl.id = 1
UNION ALL
SELECT S_Tbl.id, S_Tbl.barcode, S_Tbl.Qty, '0' as NewQty
FROM   S_Tbl where S_Tbl.id = 1

我得到了这个:

=============================
id | barcode | qty | newQty |
=============================
1 | 1234      | 10 | 20     |
1 | 1234      | 10 | 20     |
1 | 1234      | 10 | 0      |
1 | 111       | 5  | 0      |

如何合并相同的行,结果如下:

=============================
id | barcode | qty | newQty |
=============================
1 | 1234     | 10  | 20     |
1 | 1234     | 10  | 20     |
1 | 111      | 5   | 0      |

修改

我将行1 | 1234 | 10 |添加到 S_Tbl

我需要在查询中更改内容:

SELECT K_Tbl.id, K_Tbl.barcode, K_Tbl.Qty, K_Tbl.NewQty
FROM K_Tbl where K_Tbl.id = 1
UNION
SELECT S_Tbl.id, S_Tbl.barcode, S_Tbl.Qty, K_Tbl.NewQty
FROM S_Tbl 
left join K_Tbl on S_Tbl.id=K_Tbl.id and S_Tbl.barcode=K_Tbl.barcode
where S_Tbl.id = 1

我会看到

=============================
id | barcode | qty | newQty |
=============================
1 | 1234     | 10  | 20     |
1 | 1234     | 10  | 20     |
1 | 111      | 5   | 0      |

现在我看到了:

=============================
id | barcode | qty | newQty |
=============================
1 | 1234     | 10  | 20     |
1 | 111      | 5   | 0      |

2 个答案:

答案 0 :(得分:1)

SELECT K_Tbl.id, K_Tbl.barcode, K_Tbl.Qty, K_Tbl.NewQty
FROM K_Tbl where K_Tbl.id = 1
UNION
SELECT S_Tbl.id, S_Tbl.barcode, S_Tbl.Qty, K_Tbl.NewQty
FROM S_Tbl 
left join K_Tbl on S_Tbl.id=K_Tbl.id and S_Tbl.barcode=K_Tbl.barcode
where S_Tbl.id = 1

<强> SQL FIDDLE

我确信此查询可以在 MS-ACCES

中使用

答案 1 :(得分:0)

使用UNION代替UNION ALL - 速度较慢,但​​要小心重复并删除它们。请参阅MSDN文档:http://msdn.microsoft.com/en-us/library/office/bb208962(v=office.12).aspx

  

默认情况下,使用UNION时不会返回重复记录   操作;但是,您可以包含ALL谓词以确保这一点   返回所有记录。这也使查询运行得更快。

在Oracle或MSSQL中也是如此。