gpt4 book ai didi

sql - 将 SQL 查找表与数据表联接

转载 作者:行者123 更新时间:2023-12-04 22:13:23 26 4
gpt4 key购买 nike

我有一个查找表,上面写着带有 CityId、CityName 字段的城市

CityId   CityName
1 New York
2 San Francisco
3 Chicago

我有一个订单表,其中包含以下字段:CityId、CustId、CompletedOrders、PendingOrders
CityId CustId CompletedOrders PendingOrders
1 123 100 50
2 123 75 20

我想要一个表格/报告,列出所有城市中给定客户的订单详细信息,即我需要的结果是:
CityId CityName      CustId CompletedOrders PendingOrders
1 New York 123 100 50
2 San Francisco 123 75 20
3 Chicago 123 0 0

怎么做 ?

最佳答案

SELECT
c.CityId
c.CityName
o.CustId,
o.CompletedOrders
o.PendingOrders
FROM cities c
LEFT JOIN orders o ON ( c.CityId = o.CityId )

这将返回您想要的所有行,但对于 details 中不存在的行它将返回 NULL值,所以你会得到:
CityId CityName      CustId CompletedOrders PendingOrders
1 New York 123 100 50
2 San Francisco 123 75 20
3 Chicago 123 NULL NULL

得到的解决方案 0而是取决于您的数据库。与 MySQL 一起使用 IFNULL ,与 Oracle 一起使用 NVL .

关于sql - 将 SQL 查找表与数据表联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2015207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com