根据连接查询中的表名来区分记录

hem*_*iya 1 php mysql join

我使用join查询MySQL来从多个表中获取记录.我想要做的是根据表名区分记录.

例如,

1)Table1

name
test1
test2

2)Table2

name
test3
test4
Run Code Online (Sandbox Code Playgroud)

之后join它会给我这样的所有记录,

name
test1
test2
test3
test4
Run Code Online (Sandbox Code Playgroud)

我只想要这样的输出

name    from_table
test1   table1
test2   table1
test3   table2
test4   table2
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?提前致谢.

fth*_*lla 7

您不需要连接,可以使用UNION ALL查询和常量列:

SELECT name, 'table1' AS fromtable
FROM table1
UNION ALL
SELECT name, 'table2' AS fromtable
FROM table2
Run Code Online (Sandbox Code Playgroud)