0

这是我的数据库 SQL 代码;

CREATE TABLE ProductType
(
    ptID int not null auto_increment,
    pType varchar(30),
    PRIMARY KEY(ptID)
)ENGINE=InnoDB;

CREATE TABLE Service
(
    sID int not null auto_increment,
    description varchar(30) not null,
    revenue int,
    stID int not null,
    PRIMARY KEY(sID),
    FOREIGN KEY(stID) references ServiceType(stID)
)ENGINE=InnoDB;

CREATE TABLE Product
(
    pID int not null auto_increment,
    model varchar(30) not null,
    cogs int,
    ptID int not null,
    PRIMARY KEY(pID),
    FOREIGN KEY(ptID) references ProductType(ptID)
)ENGINE=InnoDB;

CREATE TABLE Sale
(
    saleID int not null auto_increment,
    assetID int not null,
    eID int not null,
    sID int not null,
    pID int,  
    saDate date not null,
    PRIMARY KEY(saleID),
    FOREIGN KEY(eID) references Employee(eID),
    FOREIGN KEY(sID) references Service(sID),
    FOREIGN KEY(pID) references Product(pID)
)ENGINE=InnoDB;

CREATE TABLE Employee
(
    eID int not null auto_increment,
    firstName varchar(30) not null,
    lastName varchar(30) not null,
    phone varchar(30),
    email varchar(30),
    PRIMARY KEY(eID)
)

这是我的尝试,但当我查询“销售”表时,我不知道如何从“服务”访问“收入”字段。

<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("pnl") or die(mysql_error());

// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM Sale WHERE saDate = CURDATE()")
or die(mysql_error());  

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry 

echo "revenue: ".$row['revenue'];

?>

谁能给我一个例子,说明我将如何编写一个 php 脚本来检索当前日期所有销售的收入?

这也是我第一次尝试 SQL 和关系数据库模型,所以如果您发现我犯的任何严重错误或我可以改进的地方,请告诉我!

4

2 回答 2

1

试试这个方法。命名 SUM 字段并通过给定名称访问它:

// Retrieve all the data from the "example" table
$result = mysql_query("SELECT SUM(Service.revenue) sum FROM Service JOIN Sale ON Sale.sID = Service.sID WHERE Sale.saDate = $some_date") or die(mysql_error());  
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry 
echo "revenue: ".$row['sum'];
于 2012-09-09T05:06:48.293 回答
0

如果销售和服务上的 sID 对每个销售都是相同且唯一的,那么您可以使用如下查询:

$result = mysql_query(SELECT Sale.saleID, Sale.assetID, Sale.eID, Sale.sID, Sale.pID, Sale.saDate, Service.revenue "."FROM Sale, Service "."WHERE Sale.sID = Service.sID AND Sale.saDate = CURDATE()) or die(mysql_error());

或者如果Service.sID = Sale.saleID然后相应地改变。

通过这种方式,您可以控制您希望从每个表中检索的确切列。

于 2012-09-09T04:28:13.897 回答