我是使用sql的新手,但我遇到了一个我似乎无法解决的问题。我有四个表:T_Item,t_trade,T_sender_trade和T_receiver_trade,如下所示:
T_Item
(itemID, name, category, description, description);
T_Trade
(tradeID, date, senderID, receiverID);
T_sender_trade
(tradeID, senderItemID) - both foreign keys from the previous tables
T_receiver_trade
(tradeID, receiverItemID) - as in T_sender_trade
这意味着发件人和收件人交易两件商品。我想要做的是使用php在html中创建一个表,其中包含以下信息:
我正在使用班级交易,因为我的老师要求。 我在课堂上使用了以下代码:
<?php
require_once '../utils/ligabd.php'; (uses the connection to the mysql in another class)
Class Trade
{
public $tradeID;
public $date;
public $senderID;
public $receiverID
public function __construct($date = null, $senderID= null, $receiverID=null) {
$this->date= $date;
$this->senderID= $senderID;
$this->receiverID= $receiverID;
}
public static function load($tradeID) {
$result = mysql_query("SELECT * FROM T_Trade");
if (!$result) {
die('Troca não existente ' . mysql_error());
}
$row = mysql_fetch_assoc($result);
if ($row) {
$t = new Trade();
$t->tradeID = $row["tradeID"];
$t->date = $row["date"];
$t->senderID=$row["senderID"];
$t->receiverID=$row["receiverID"];
return $t;
} else {
return NULL;
}
}
public static function returnsSenderItem($tradeID) {
$result = mysql_query("SELECT * FROM T_Item, T_sender_trade where T_sender_trade.tradeID= $tradeID AND T_sender_trade.senderItemID =T_Item.ItemID");
if(!$result) {
die ('Trade not found ' .mysql_error());
}
$rows=Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[]=$row;
}
return $rows;
}
对于接收者的项目也一样。 在我使用的PHP代码中(只是为了获得一个项目的描述,因为我能够获得ttade的日期):
include '../classes/troca.php';
$tradeID=$_GET[tradeID];
$trade=Trade::load($tradeID);
echo $trade->date;
$sender=Trade::returnsSenderItem($tradeID);
foreach($senderr as $s):
echo $s['name'];
endforeach;
我应该使用这样的代码来制作我的表格。事情是程序无法从T_Item中找到数据..我应该在我的类/ php中更改它应该怎么做? 谢谢。
答案 0 :(得分:0)
为了获得发件人和收件人项目的描述,您需要链接到T_Item表两次(每个项目一次) - 这将需要使用表别名,如此:
select t.tradeID,
t.`date`,
t.senderID,
s.SenderItemID,
si.description as SenderDescription,
t.receiverID,
r.ReceiverItemID,
ri.description as ReceiverDescription
from T_Trade as t
join T_sender_trade as s on t.tradeID = s.tradeID
join T_Item as si on s.senderItemID = si.itemID
join T_receiver_trade as r on t.tradeID = r.tradeID
join T_Item as ri on s.receiverItemID = ri.itemID
where t.tradeID = $tradeID