【发布时间】:2016-07-23 19:53:58
【问题描述】:
我将简要解释一下我到目前为止所做的事情-
首先,我有多家商店,每家商店都有自己的表,其中包含 id、item、qty 和 price,还有一个名为 all_items 的主表,其中包含从每个商店的桌子。
现在每个商店表要么具有相同的项目编号,要么不同。在这里您可以看到表格的样子:
存储表称为:S1、S2、S3
S1
id item qty price
1 x1 10 12
2 x2 10 15
3 x3 5 5
S2
id item qty price
1 x1 10 12
2 x4 6 6
S3
id item qty price
1 x3 1 5
2 x6 5 5
3 x7 5 12
all_items - 包含原始总数量
id item qty price
1 x1 20 12
2 x2 10 15
3 x3 6 5
4 x4 6 6
5 x6 5 5
6 x7 5 12
好的,我决定找出所有商店中每件商品的可用数量以进行比较 - 如下:
item price S1 S2 S3
x1 12 10 10 -
x2 15 10 - -
x3 5 5 - 5
x4 6 - 6 -
x6 5 - - 5
x7 12 - - 5
我希望你现在清楚了。我创建了一个带有复选框输入类型的表单(针对每个商店),以允许用户选择他想要比较的商店,因此在提交表单后 - PHP 页面包含以下代码:
$allstore = $_POST['store']; //Collects name from checkbox ticks under form
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = "all_items";
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
$allstore = array(); // The below code allows function to know how many stores selected in $allstore
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore["s_".$value] = 0; // or 1, it doesn't matter because your function adds all the keys
}
}
var_dump(createSelect($allstore)); // Output SQL
$query = (createSelect($allstore));
$result = mysql_query($query);
//Rest of the code .....
现在,如果您注意到 $baseTable = "all_items"; 会使整个查询失败。但是,如果我将它的值更改为$baseTable = $store;,它会工作并显示输出,但不会像预期的那样,因为现在 S1 是主要的,结果将完全不同,因为它仅在 S1 项目上中继。
如果您能提供任何有用的解决方案,我们将不胜感激。
【问题讨论】:
标签: php join left-join inner-join