我有一个包含产品的表,另一个包含变体的表和第三个包含产品变化的表(许多产品可以有许多变化......两种方式)。我想显示(分组)每个产品并显示变化。
我读到的只是循环直播并比较id以查看你所在的记录,如果新记录然后调整输出......看起来并不干净。
答案 0 :(得分:0)
如果您正在编写SQL,那么您的选择可以是进行比较的一个查询,也可以是依赖于第一个查询的许多查询。另一方面,ADOdb for PHP具有ActiveRecords,它可以为您处理一对多关系。 http://phplens.com/lens/adodb/docs-active-record.htm#onetomany
答案 1 :(得分:0)
我建议修改你的SQL以显示你想要的数据,这样就不需要手动修改数据了。 group by clause或order by clause可能是您的朋友。
答案 2 :(得分:0)
我更喜欢使用缓存Sytem。
在PHP中实现缓存
<?php
// start the output buffer
ob_start(); ?>
//Your usual PHP script and HTML here ...
<?php
$cachefile = "cache/home.html";
// open the cache file "cache/home.html" for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
?>
使用缓存文件
<?php
$cachefile = "cache/home.html";
if (file_exists($cachefile)) {
// the page has been cached from an earlier request
// output the contents of the cache file
include($cachefile);
// exit the script, so that the rest isnt executed
exit;
}
?>
答案 3 :(得分:0)
我认为您正在寻找一种方法来列出单个产品及其所有变体。或者列出所有产品,然后为每个产品列出该产品的每个变体。
我假设你的表看起来像这样:
product
productId
description
variation
variationId
description
productVariation
productVariationId
productId
variationId
对于单个产品及其所有变体,您可以使用以下查询,即执行两个内部联接。
SELECT
P.description as product,
V.description as variation
FROM
product as P,
INNER JOIN
productVariation AS PV
ON PV.productId = P.productId
INNER JOIN
variation as V
ON V.variationId = PV.variationId
WHERE
P.productId = 1
对于整个产品列表,只需省略WHERE子句。 如果产品没有变化,它将不会包含在列表中。如果需要,请改用LEFT JOIN。
查询将返回以下内容
product variation
shoe blue
shoe green
shoe red
hat green
hat purple
hat yellow
sock white
更新
我猜您希望数据显示如下:
shoe
blue
green
red
hat
green
purple
yellow
sock
white
可以通过以下PHP代码完成。
$sql = "
SELECT
P.productId,
P.description as product,
V.description as variation
FROM
product as P,
INNER JOIN
productVariation AS PV
ON PV.productId = P.productId
INNER JOIN
variation as V
ON V.variationId = PV.variationId
";
$result = mysql_query($sql);
//first put all the results into an array so we can look backward and
//see previous items
$resultSet = array();
while($record = mysql_fetch_array($result)) {
$resultSet[] = $record;
}
for ( $i = 0 ; $i < count($resultSet) ; $i++ ) {
if ( $i == 0 ) {
//for the first item, show the product name
echo $resultSet[$i]['product'].'<br/>';
} else if ($resultSet[$i]['productId'] != $resultSet[$i-1]['productId']) {
//every time we encounter a new product
//display a new line and show the product name
echo '<br/>'.$resultSet[$i]['product'].'<br/>';
}
echo $resultSet[$i]['variation'].'<br/>';
}