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

时间:2015-02-11 09:48:06

标签: mysql tablename

我正在尝试整理一个MySQL查询,它将搜索2个表,table1和table2,并在两个表中选择所有不到30天的结果。

我的桌子:

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查询很新。提前谢谢,

1 个答案:

答案 0 :(得分:0)

您应该使用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