【问题标题】:How do I search for an entry out of two SQL tables and know which table it came from?如何从两个 SQL 表中搜索条目并知道它来自哪个表?
【发布时间】:2020-11-21 22:52:09
【问题描述】:

我正在尝试查找特定条目。此条目只能出现在我的两个表中的一个中,并且永远不会在任何一个表中重复。

这是我的表格的缩小版本示例:

表 1:

Date             Name              Room
2020/01/23       John              201
2020/01/22       Rebecca           203

表 2(列数不同):

Date             Name              
2020/01/23       Robert            
2020/01/22       Sarah             

要查找此条目,我需要指定日期和名称。您可以假设名称从不重复。

假设我想找到莎拉 2020/01/22

她可以出现在表 1 或表 2 中,我不知道是哪一个,我需要知道她在哪一个表中。

我不确定如何在单个 SQL 查询中执行此操作。到目前为止,我只有两个独立的:

SELECT date,name from Table1 WHERE name="Sarah" and date='2020/01/22'

SELECT date,name from Table2 WHERE name="Sarah" and date='2020/01/22'

有没有办法在单个查询中执行此操作,同时告诉我它来自哪个表?这可能是我能得到的另一个领域或一些迹象。谢谢。

【问题讨论】:

    标签: mysql sql database union where-clause


    【解决方案1】:

    使用union all,并为每个结果集添加另一列,其文字值指示表名:

    select 't1' as which, date, name from table1 where name = 'Sarah' and date = '2020-01-22'
    union all 
    select 't2' as which, date, name from table2 where name = 'Sarah' and date = '2020-01-22'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多