gpt4 book ai didi

mysql查询从2个表中选择*值并返回结果存在的表的名称?

转载 作者:行者123 更新时间:2023-11-29 23:01:49 26 4
gpt4 key购买 nike

我正在尝试组合一个 MySQL 查询,该查询将搜索 2 个表(table1 和 table2),并选择任一表中 30 天以内的所有结果。

我的 table :

table1

id | user_id | name | age | date |


table2

id | user_id | name | age | date | account | sortcode |

我像这样回显结果:

    <?php require_once 'config.php'; ?>

<?php
$table1 = 'supplier_bank_details';
$table2 = 'supplier_invoices';

$query = "SELECT *, $table1 as TABLE from $table1 where
date > NOW() - INTERVAL 30 DAY and user_id = '{$_SESSION['id']}' ORDER BY date DESC
UNION
SELECT *, $table2 as TABLE from $table2 where
date > NOW() - INTERVAL 30 DAY and user_id = '{$_SESSION['id']}' ORDER BY date DESC";
$result = mysql_query($query) or die( mysql_error() );
while($row = mysql_num_fields($result)){


if($result === $table1) {

echo 'this result is from table1';
echo $row['name'];
echo $row['age'];

}else{

if($result === $table2) {

echo 'this result is from table2';
echo $row['name'];
echo $row['age'];


} } }
?>

所以基本上我试图设置一个条件来检查结果来自哪个表,并回显“结果来自表 1/2”以及该表中的值。

有谁知道我该怎么做,因为我对 MySQL 查询还很陌生。提前致谢,

最佳答案

您应该使用union来实现此目的。此外,您可以使用结果集本身对表的值($table1 或 $table2)进行硬编码。

Select id, user_id, name, age, date, TABLE
from
(
SELECT id, user_id, name, age, date, $table1 as TABLE from $table1 where
date > NOW() - INTERVAL 30 DAY and user_id = '{$_SESSION['id']}'
UNION
SELECT id, user_id, name, age, date, $table2 as TABLE from $table2 where
date > NOW() - INTERVAL 30 DAY and user_id = '{$_SESSION['id']}'
)
ORDER BY date DESC

关于mysql查询从2个表中选择*值并返回结果存在的表的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28451134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com