如何使用MySQL进行一系列不同的查询

时间:2013-04-17 15:53:18

标签: mysql sql select

我想知道怎么做!!!。

现在: 我有卖家分组,提供宠物

宠物在一张名为 PetTable 的表格中(PETCode和PETName)

CREATE TABLE PetTable ( 
PETCode VARCHAR(16) UNIQUE NOT NULL, 
PETName VARCHAR(32) NOT NULL 
);
INSERT INTO PetTable (PETCode, PETName) VALUES 
('Pet1','Black Cat'), 
('Pet2','Big Dog'), 
('Pet3','Gold Fish'), 
('Pet4','Parlot'), 
('Pet5','Bird'), 
('Pet6','Small Dog'); 

卖家存储在 SellerTable (CodeSeller和NameSeller)

CREATE TABLE SellerTable  ( 
CodeSeller VARCHAR(16) UNIQUE NOT NULL, 
NameSeller VARCHAR(32) NOT NULL 
); 
INSERT INTO SellerTable  (CodeSeller, NameSeller) VALUES 
('Seller0','John '), 
('Seller1','Paul '), 
('Seller2','David '),   
('Seller3','James ');

卖家与宠物有关,使用 SalesTable 有3个字段(PETCode,CodeSeller,Quantity)

CREATE TABLE SalesTable ( 
PETCode VARCHAR(16) NOT NULL, 
CodeSeller VARCHAR(16) NOT NULL, 
Quantity INT NOT NULL 
);
INSERT INTO SalesTable (PETCode, CodeSeller, Quantity) VALUES 
('Pet1', 'Seller0', '9'), 
('Pet2', 'Seller0', '81'), 
('Pet3', 'Seller0', '7'), 
('Pet4', 'Seller1', '63'), 
('Pet5', 'Seller1', '4'), 
('Pet6', 'Seller1', '50'), 
('Pet2', 'Seller2', '61'), 
('Pet5', 'Seller2', '72'), 
('Pet4', 'Seller3', '83'), 
('Pet2', 'Seller3', '94'), 
('Pet1', 'Seller3', '8'); 

我的查询非常简单,如何知道每张PET的销售额! 什么是PET1,PET2,PET3的所有销售总和......并继续...

感谢您的宝贵帮助......

2 个答案:

答案 0 :(得分:0)

您需要将PetTableSalesTable一起加入PetTable.PetCode = SalesTable.PetCode,并且由于他们共有的列具有相同的名称,您可以使用NATURAL JOIN

SELECT PETName, SUM(Quantity)
FROM PetTable NATURAL JOIN SalesTable
GROUP BY PETName

请参阅小提琴here

或者如果您只需要按PETCode进行SUM,并且您对宠物名称不感兴趣,则可以在没有加入的情况下使用它:

SELECT PETCode, SUM(Quantity)
FROM SalesTable
GROUP BY PETCode

答案 1 :(得分:0)

您需要先加入表格。由于您对SellerName不感兴趣,因此使用PetTable与表SalesTable加入表LEFT JOIN即可满足您的需求。

在我的查询中使用LEFT JOIN超过INNER JOIN的原因是因为它仍然包含尚未售出的Pets

SELECT  a.PETCode,
        a.PETName,
        SUM(b.Quantity) TotalSold
FROM    PetTable a
        LEFT JOIN SalesTable b
            ON a.PETCode = b.PETCode
GROUP   BY  a.PETCode, a.PETName

要进一步了解联接,请访问以下链接:

输出

╔═════════╦═══════════╦═══════════╗
║ PETCODE ║  PETNAME  ║ TOTALSOLD ║
╠═════════╬═══════════╬═══════════╣
║ Pet1    ║ Black Cat ║        17 ║
║ Pet2    ║ Big Dog   ║       236 ║
║ Pet3    ║ Gold Fish ║         7 ║
║ Pet4    ║ Parlot    ║       146 ║
║ Pet5    ║ Bird      ║        76 ║
║ Pet6    ║ Small Dog ║        50 ║
╚═════════╩═══════════╩═══════════╝