php - 检索两个独立列的总和 - 使用嵌套选择语句
问题描述
本质上,我试图在书店内显示书籍的 ID、标题、总数量和总销售价格。目前我能够显示 ID、标题和总数量 - 或者 ID、标题和总销售价格,但是我无法弄清楚如何从该表中同时检索总数量和销售价格.
此查询成功地为我提供了 ID、标题和数量:
SELECT ID,Title,(SELECT Sum(Quantity) from Sale where BookId = Book.id ) as Quantity from Book;
此查询成功地为我提供了 ID、标题和销售价格:
SELECT ID,Title,(SELECT Sum(UnitPrice) from Sale where BookId = Book.id ) as Price from Book;
那么如何在我们的查询中同时检索 Quantity 和 Sales Price 呢?这两个值都在同一个表中,但这里使用了两个表。
这是我当前用来循环并显示查询结果的 HTML:
<!DOCTYPE html>
<html lang="en">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="new.css">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-default navbar navbar-inverse">
<div class="container">
<h2> <a class="head" href="base.php" style="text-decoration: none;">Database Project</a> <a class="btn btn-danger btn-sm main" href="login.php" role="button">Sign Out</a></h2>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>Book Report:</h1><br>
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Quantity</th>
<th>Total Sale Price</th>
</tr>
<?php
$conn = mysqli_connect("localhost","root","","Zion");
if ($conn-> connect_error){
die("Connection Failed:". $conn-> connect_error);
}
$sql = "SELECT ID,Title,(SELECT Sum(Quantity) from Sale where BookId = Book.id ) as Quantity,(SELECT Sum(UnitPrice) from Sale where BookId = Book.id ) as Price from Book";
$result = $conn-> query($sql);
if ($result = $conn->query($sql)) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["ID"] . "</td><td>". $row["Title"]."</td><td>". $row["Quantity"]. "</td><td>". "$".$row["Price"]. "</td></tr>";
}
echo"</table>";
}
$conn-> close()
?>
<!-- Generate a report that for each book, displays the book id, the book title,
the quantity and the total sales price, sorts by the book id in increasing order; -->
</div>
</body>
</html>
谢谢!
解决方案
美好的一天,你可以试试这个查询
SELECT ID,Title,(SELECT Sum(Quantity) from Sale where BookId = Book.id ) as Quantity,(SELECT Sum(UnitPrice) from Sale where BookId = Book.id ) as Price from Book;
推荐阅读
- r - 如何在 R 中设置不同的中断和剪切数据
- node.js - 如何查询以达到最高点的排名文档
- sql - 在 SQL 中获取具有特定条件的行数
- wolfram-mathematica - 在 Mathematica 中进行代数替换的问题
- javascript - 如何在 discord.js 的不和谐语音频道中静音/取消静音?
- r - R 在行内的多个条件上使用 any()
- visual-studio-code - VSCode 中未使用变量的语义高亮显示
- css - 盖茨比、MaterialUI 制作中的 css 中断
- pytorch - PyTorch 中torch.embedding 的定义在哪里?
- laravel - 使用邮件陷阱向用户发送验证电子邮件后将用户重定向到登录页面