是否可以构建一组 SQL 命令来查询数据库?我所拥有的是三个表,每个表都有到期金额的列。想选择任何到期并显示在屏幕上的东西,以便可以开具发票(最好在表格中),并且每一行都有各自的客户会费。
我可以在三个表之间使用 UNION ALL 选择所有到期的内容,但是我不知道如何在表行中按 ID 列出它们。
以下是我到目前为止所拥有的。按照这个速度,我必须分别运行每个查询并将它们列在三个单独的列表中。建议?
<table>
<tr>
<th> ID</th>
<th> Cost 1</th>
<th> Cost 2</th>
<th> Cost 3</th>
</tr>
<?php
$list1 = "SELECT ID, Cost FROM Table1 WHERE Invoiced IS NULL;";
//$list2 = "SELECT ID, Price2 FROM Table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate';";
//$list3 = "SELECT ID, Price3 FROM Table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'";
$result = mysql_query($list1, $link) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$num_fields = mysql_num_fields($result);
for ($i=0; $i<$num_rows; $i++) {
for ($j=0; $j<$num_fields; $j++) {
$invoice[$i][mysql_fieldname($result,$j)] = mysql_result($result,$i,mysql_field_name($result,$j));
}
}
//eventually the order it should be listed on screen
for($i=0; $i<count($invoice); $i++) {
echo "<tr><td>".$invoice[$i]["ID"]."</td>
<td>".$invoice[$i]["Cost"]."</td>
<td>".$invoice[$i]["Price2"]."</td>
<td>".$invoice[$i]["Price3"]."</td></tr>";
}
?>
</table>
评论后编辑:
查询被传递并返回语法错误You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'all LEFT JOIN table1 ON all.ID = table1.ID LEFT JOIN t' at line 7
:
$query = "
SELECT all.ID, table1.Cost1, table2.Price2, tabl3.Price3
FROM
(SELECT ID, Cost1 FROM table1 WHERE Invoiced IS NULL
UNION
SELECT ID, Price2 FROM table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'
UNION
SELECT ID, Price3 FROM table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') AS all
LEFT JOIN table1 ON all.ID = table1.ID
LEFT JOIN table2 ON all.ID = table2.ID
LEFT JOIN table3 ON all.ID = table3.ID
";