0

顾客

╔═══════╦══════════╗
║ CUSID ║ CUS NAME ║
╠═══════╬══════════╣
║     1 ║ AA       ║
║     2 ║ BB       ║
║     3 ║ CC       ║
╚═══════╩══════════╝

库斯海鲜

╔════╦═══════╦══════════╗
║ ID ║ CUSID ║   NAME   ║
╠════╬═══════╬══════════╣
║  1 ║     1 ║ SeaFoodA ║
║  2 ║     1 ║ SeaFoodB ║
║  3 ║     2 ║ SeaFoodC ║
╚════╩═══════╩══════════╝

库斯比萨

╔════╦═══════╦══════╗
║ ID ║ CUSID ║ NAME ║
╠════╬═══════╬══════╣
║  1 ║     1 ║ PAA  ║
║  2 ║     2 ║ PBB  ║
╚════╩═══════╩══════╝

库斯小吃

╔════╦═══════╦══════╗
║ ID ║ CUSID ║ NAME ║
╠════╬═══════╬══════╣
║  1 ║     2 ║ SAA  ║
║  2 ║     3 ║ SBB  ║
╚════╩═══════╩══════╝

想计算以下客户示例订购了多少海鲜、比萨饼或小吃。

Cus ID, Cus Name, Number Of SeaFood, Sea Food info, Number Of Pizza, Pizza info, Number of Snack, Snack info.

客户可能不会订购所有 3 种食物。

4

2 回答 2

4

您需要通过子查询单独计算每个计数,以便获得正确的结果。这将防止您计算重复记录。

SELECT  a.*,
        COALESCE(b.totalSeaFood, 0) totalSeaFood,
        COALESCE(c.totalPizza, 0) totalPizza,
        COALESCE(d.totalSnack, 0) totalSnack
FROM    Customer a
        LEFT JOIN
        (
            SELECT  cusID, COUNT(*) totalSeaFood
            FROM    CusSeaFood
            GROUP   BY cusID
        ) b ON a.cusID = b.CusID
        LEFT JOIN
        (
            SELECT  cusID, COUNT(*) totalPizza
            FROM    CusPizza
            GROUP   BY cusID
        ) c ON a.cusID = c.CusID
        LEFT JOIN
        (
            SELECT  cusID, COUNT(*) totalSnack
            FROM    CusSnack
            GROUP   BY cusID
        ) d ON a.cusID = d.CusID

要进一步了解有关联接的更多信息,请访问以下链接:

结果

╔═══════╦══════════╦══════════════╦════════════╦════════════╗
║ CUSID ║ CUS NAME ║ TOTALSEAFOOD ║ TOTALPIZZA ║ TOTALSNACK ║
╠═══════╬══════════╬══════════════╬════════════╬════════════╣
║     1 ║ AA       ║            2 ║          1 ║          0 ║
║     2 ║ BB       ║            1 ║          1 ║          1 ║
║     3 ║ CC       ║            0 ║          0 ║          1 ║
╚═══════╩══════════╩══════════════╩════════════╩════════════╝
于 2013-03-07T07:20:47.547 回答
1

您的示例中的“海鲜信息”,“披萨信息”等对我来说没有意义。如果客户订购了不止一种海鲜或比萨饼,那么这里应该如何表示?

通常你会期望看到多行,每个订购的东西一个。要获取此信息,您甚至不需要加入,只需一个UNION.

SELECT * FROM CusSeaFood WHERE CusID = ?
UNION SELECT * FROM CusPizza WHERE CusID = ?
UNION SELECT * FROM CusSnack WHERE CusID = ?
于 2013-03-07T07:21:54.380 回答