How do I search for an entry out of two SQL tables and know which table it came from?

PSU Change

I'm trying to find a specific entry. This entry can appear in only ONE of my two tables and will never repeat in either table.

Here is a scaled-down version example of my tables:

Table 1:

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

Table 2 (does NOT have the same amount of columns):

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

To find this entry, I need to specify a date and a name. You can assume names never repeat.

So let's say I want to find Sarah 2020/01/22

She could appear in either Table 1 or Table 2, and I don't know which one and I need to know which table she's in.

I'm not sure how I would do this in a single SQL query. So far I just have two separate ones:

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

and

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

Is there a way to do it in a single query that also tells me which table it came from? It could be another field or some indication that I can get. Thanks.

GMB

Use union all, and add another column to each resulset, with a literal value that indicates the table name:

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'

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

How can I find which tables reference a given table in Oracle SQL Developer?

How do i navigate to another view from search results displayed in table view?

How do you know which interface a broadcast message came from?

How do I print out the table name of a sequelize instance?

How do I filter out random sample from dataframe in which there are different sample size for each value, in python?

SQL on Oracle: Already joined two tables, now i want another column from another table(another join)

How do I make two unordered list fade in and fade out when my menu is clicked depending on which is showing?

How do CakePHP callback functions know that $q is a Query object and which table to execute the query on?

SQL - join TWO tables and get record from B table if exist, else from A table

Conda: how should I know from which channel I got a package

How do I stack multiple frequency tables into one table in R?

How can I find out which tables and stored procedures a database user has accessed?

How do I know which GPUs a job was allocated using SLURM?

How do I delete entries from two two-column tables such that their second columns match within a certain error

How do I create a function for two-dimensional array search?

How can I figure out where a log message came from (and disable it)?

How do you know which conda channel to install from?

How can I join data from two tables and insert the result into a new table?

How do I know which variant of Firefox OS is on my phone?

How to find MAX value from two tables in SQL Server?

How to compare data from two tables in sql?

How to perform an SQL query from a table based on values in other tables?

How do I know which value is selected

How can i join two tables with two columns that refers the same column in the second table in SQL Server

How do i select dropdown values which is outside from easyui datagrid table

How do I print out one factorial number? My code keeps printing out too many numbers and I do not know why?

How do I compare two columns from different tables in different databases?

How to optimize this SQL query which select from the same table twice

How can I merge two SQL tables and then append the result to a third?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    How to click an array of links in puppeteer?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    Нарисуйте диаграмму с помощью highchart.js

  6. 6

    无法通过Vue在传单中加载pixiOverlay

  7. 7

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  8. 8

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  9. 9

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  10. 10

    ContentDialog.showAsync в универсальном оконном приложении Win 10

  11. 11

    В UICollectionView порядок меняется автоматически

  12. 12

    Merging legends in plotly subplot

  13. 13

    Elasticsearch - Нечеткий поиск не дает предложения

  14. 14

    Bogue étrange datetime.utcnow()

  15. 15

    Объединение таблиц в листе Google - полное соединение

  16. 16

    Single legend for Plotly subplot for line plots created from two data frames in R

  17. 17

    как я могу удалить vue cli 2?

  18. 18

    ViewPager2 мигает / перезагружается при смахивании

  19. 19

    Компилятор не знает о предоставленных методах Trait

  20. 20

    JDBI - В чем разница между @define и @bind в JDBI?

  21. 21

    проблемы с AVG и LIMIT SQL

популярныйтег

файл