简体   繁体   English

获取具有相同列数据的多个表

[英]get multiple table with same columns data

i have three table with same value of columns.我有三个列值相同的表。 example: say i have three table " table1 ", " table2 ", " table3 " and each columns has " id ", " title ", " description ", " category ", " date ", " thumbnail ", " admin ".示例:假设我有三个表“ table1 ”、“ table2 ”、“ table3 ”,每列都有“ id ”、“ title ”、“ description ”、“ category ”、“ date ”、“ thumbnail ”、“ admin ”。 now i'm trying to get all data from those three table.现在我正试图从这三个表中获取所有数据。 but there is a think, i want to check with if statement .但是有一个想法,我想用if 语句检查一下。 if table1 not match with id, check table2 .如果table1与 id 不匹配,请检查table2 if table2 not match with id, check table3 and at last show the data.如果 table2 与 id 不匹配,请检查table3 ,最后显示数据。 please check my below code, i'm trying to get data from those three table:请检查我下面的代码,我正在尝试从这三个表中获取数据:

<?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'];
         }
          ?>

please help me to get all data from those three table with if statement it will be better to understand if you post an answer.请帮助我使用if 语句从这三个表中获取所有数据,如果您发布答案会更好地理解。 thank you in advance.先感谢您。

Use a UNION of 3 queries.使用 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'];
}

Adding the tnum column to the result orders them so the table1 data is preferred, then table2 , finally table3 .tnum列添加到结果中对它们进行排序,以便首选table1数据,然后是table2 ,最后是table3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM