SQL查询从当前日期检索字段

时间:2012-09-09 03:52:51

标签: php sql

这是我的数据库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和关系数据库模型,所以如果你发现我做过的任何重大错误或者我可以改进的事情,请告诉我!

2 个答案:

答案 0 :(得分: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'];

答案 1 :(得分: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然后相应改变。

通过这种方式,您可以精确控制从每个表中检索哪一列。