如何在一个SQL查询中连接两个SELECT语句?

2019年11月24日 37点热度 0条评论 来源: Mohit Sachdev

我们怎样才能一次选择两个表,并得到如何在一个SQL查询中连接两个SELECT语句?

<?php 
$id= null; 
@$id = $_REQUEST['id']; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT ID, name, gender, age, contact, village, town, id_proof, id_proof_no, reg_date 
FROM milk_man_profile WHERE ID=$id 
UNION 
SELECT date, time, amount, particular FROM debit WHERE ID=$id"; 

$result = $conn->query($sql); 

if (@$result->num_rows > 0) { 

    // output data of each row 
    while($row = $result->fetch_assoc()) { 
    echo "<h3 style='text-align: center; font-family: verdana;'>Profile Details</h3>"; 
    echo "<form action='milk_edit_profile.html?id=$id' method='get'><div class='container'><div class='table-reponsive text-center'><table class='table table-bordered table-striped'> 
     <tr><th>ID:</th><td class='text-center'><input readonly style='text-align: center; border: 0px solid;' type='text' name='id' value='".$row['ID']."'></td></tr> 
     <tr><th>Name:</th><td>".$row['name']."</td></tr> 
     <tr><th>Reg. Date:</th><td>".$row['reg_date']."</td></tr> 
     <tr><th>Age (Reg. Date)</th><td>".$row['age']."</td></tr> 
     <tr><th>Gender:</th><td>".$row['gender']."</td></tr> 
     <tr><th>Contact No:</th><td>".$row['contact']."</td></tr> 
     <tr><th>Village:</th><td>".$row['village']."</td></tr> 
     <tr><th>Town:</th><td>".$row['town']."</td></tr> 
     <tr><th>".$row['id_proof']." No:</th><td>".$row['id_proof_no']."</td></tr> 
    <tr><td colspan='2' class='text-center'><button type='submit' class='btn btn-info'>Edit Details <span class='glyphicon glyphicon-edit'></span></button></td> 
    </tr></table></div></div></form><br/> 

    <div class='container'> 
    <div class='table-responsive'> 
     <table class='table table-bordered table-striped'> 
     <th class='text-center'><b>Date & Time</b></th> 
     <th class='text-center'><b>Type</b></th> 
     <th class='text-center'><b>Amount</b></th> 
     </table> 
    </div> 
    </div> 
     <div class='text-center'> 
     <form action='/milk_e_ledger/debit.html?'> 
     <input type='hidden' name='debiter_name' method='get' value='".$row['name']."'> 
     <input type='hidden' name='id' method='get' value='$id'> 
     <br/> 
     <button class='btn btn-danger'>Debit Money <span class='glyphicon glyphicon-usd'></span></button></form></div><br/>"; 
} 
} 
else { 
    echo("Error description: " . mysqli_error($conn)); 
    } 
$conn->close(); 

?> 

然后我收到以下错误数据:

The used SELECT statements have a different number of column

我如何可以一次选择两个表中的信息? < ------------------->


===========解决方案如下:

尝试在您的SQL语句中使用JOIN。

这帮助我,当我开始与SQL:
https://www.w3schools.com/sql/sql_join.asp

    原文作者:Mohit Sachdev
    原文地址: https://stackoverflow.com/q/46564838
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。