簡體   English   中英

獲取具有相同列數據的多個表

[英]get multiple table with same columns data

我有三個列值相同的表。 示例:假設我有三個表“ table1 ”、“ table2 ”、“ table3 ”,每列都有“ id ”、“ title ”、“ description ”、“ category ”、“ date ”、“ thumbnail ”、“ admin ”。 現在我正試圖從這三個表中獲取所有數據。 但是有一個想法,我想用if 語句檢查一下。 如果table1與 id 不匹配,請檢查table2 如果 table2 與 id 不匹配,請檢查table3 ,最后顯示數據。 請檢查我下面的代碼,我正在嘗試從這三個表中獲取數據:

<?php
            include('config/database.php');
            $id=$_GET['single'];
            $query=mysqli_query($conn,"select * from table1, table2, table3 where id='$id'  ");
            while($row=mysqli_fetch_array($query)){
            $title=$row['title'];
            $date=$row['date'];
            $admin=$row['admin'];
            $thumbnail=$row['thumbnail'];
            $description=$row['description'];
            $category=$row['category'];
         }
          ?>

請幫助我使用if 語句從這三個表中獲取所有數據,如果您發布答案會更好地理解。 先感謝您。

使用 3 個查詢的UNION

$sql = "
    SELECT * FROM (
        SELECT 1 AS tnum, * FROM table1 WHERE id = ?
        UNION ALL
        SELECT 2 AS tnum, * FROM table2 WHERE id = ?
        UNION ALL
        SELECT 3 AS tnum, * FROM table3 WHERE id = ?
    ) AS x
    ORDER BY tnum
    LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iii', $id, $id, $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row) {
    $title = $row['title']
    $date=$row['date'];
    $admin=$row['admin'];
    $thumbnail=$row['thumbnail'];
    $description=$row['description'];
    $category=$row['category'];
}

tnum列添加到結果中對它們進行排序,以便首選table1數據,然后是table2 ,最后是table3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM