Suppose there are two tables, provided that the columns in them are identical, but the id in them is unique, i.e. in table 1 there can be no id which already exists in table 2. I have a certain value, I need to determine in which table it is located, I write a query with the union of two tables for its search

SELECT t.id FROM ( SELECT id FROM table_1 UNION SELECT id FROM table_2 ) as t WHERE t.id = "22" 

The query works, and I can get the result - there is a given value in which of the tables or not. The task is in this way, I pass a certain value and if there is one, then get the name of the table in which it is located. enter image description here

  • It would be entirely appropriate if you publish your decision as an answer - Anton Shchyrov
  • can you find out why this is necessary? Just some kind of strange logic for 2 tables in this case? - varz62
  • Well, I did a multi-level menu for the site, and decided to split each subcategory into several tables, so as not to get confused, I got 2 tables, because the record goes into them from the admin written in php, I provided a unique id, which is used to form links, in general there tricky), I am still in this novice, and in general I have invented such logic, but the name is needed for a small pagination (for example, for example, main> category1> category2 above). There, too, it is tricky, I pass the identifier to the input, use it to determine the degree of nesting by request and form pagination on its basis - veti4
  • @ varz62 could of course make one table and add an additional field in which the nesting level would be indicated (category 1> category 1.1, category 1.2 (such hierarchy)) but it seemed to me that with two tables it would be easier in the sense that everything is more structured veti4
  • it is not easier to make a table of the form id parent_id category there are ready-made solutions or nested sets for a category there is a bunch of worked-out solutions - varz62

1 answer 1

Deduced the name of the table as follows:

 SELECT t.id, t.tablename FROM ( SELECT 'table1' as tablename, id FROM table_1 UNION SELECT 'table2' as tablename, id FROM table_2 ) as t WHERE t.id = "22"