0

我有两张桌子。一个用于销售员,另一个用于销售 我希望按销售员姓名的 ALPHA 排序查询输出。

这是表结构:

CREATE  TABLE `Salesman` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Name` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Salesman` (`Name`) VALUES ('Bill');
INSERT INTO `Salesman` (`Name`) VALUES ('John');
INSERT INTO `Salesman` (`Name`) VALUES ('Dave');
INSERT INTO `Salesman` (`Name`) VALUES ('Mark');


CREATE  TABLE `Sales` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Item` INT VARCHAR(45) NULL ,
  `Salemesman_ID` INT NULL ,
  `Total` INT NUll ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES ('Pen', '3', '14');
INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES ('Rat', '1', '12');
INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES ('Car', '2', '1230');
INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES('Rabbit', '2', '11');
INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES('Towel', '1', '6');
INSERT INTO `Sales` (`Item`, `Salemesman_ID`, `Total`) VALUES('VaporWare', '4','900');

因为 Salesmen 中的姓名按 Alpha 顺序依次为:Bill、Dave、John、Mark

我需要输出

Rat         1  12              (Bill = 1)
Towel       1  6               (Bill = 1)
Pen         3  14              (Dave = 3)
Car         2   1230           (John = 2)
Rabbit      2    11            (John = 2)
VaporWare   4    900           (Mark = 4)
4

1 回答 1

4

您可以通过将表连接在一起来做您想做的事情:

select s.*
from sales s join
     SalesMan sm
     on s.Salesman_Id = sm.Id
order by sm.name, sm.id;

我觉得有必要补充一点,表名“Salesman”似乎不必要地限制了一半的人类。

于 2013-05-22T01:08:02.300 回答