简体   繁体   English

SQL查询找到表名

[英]SQL query to find the table name

I have 5 different tables in my dB with the structure Name|Price|Id.. 我的dB中有5个不同的表,其结构为Name|Price|Id..

I have a unique price and Id entry combination. 我有独特的价格和ID输入组合。

Using these 2, what could be the possible SQL query to fetch the name of the table in which this entry is present? 使用这些2,可能会有什么SQL查询来获取存在该条目的表的名称?

I need to fetch the name of this table in order to update the value of Price. 我需要获取此表的名称以更新Price的值。

You really should normalise your database properly and use a single table, but if you really need a kludge then: 您确实应该正确地规范化数据库并使用单个表,但是如果您确实需要kludge,则:

SELECT name, brand, id, 'Tea' as tablename
  FROM TableTea
 WHERE brand = 'abc'
   AND id = 100
UNION
SELECT name, brand, id, 'Coffee' as tablename
  FROM TableCoffee
 WHERE brand = 'abc'
   AND id = 100
UNION
SELECT name, brand, id, 'Chocolate' as tablename
  FROM TableChocolate
 WHERE brand = 'abc'
   AND id = 100

And you'll have to change it if you ever add new products 如果您要添加新产品,就必须更改它

if your DBMS is MySQL you can use this Query: 如果您的DBMS是MySQL,则可以使用以下查询:

SELECT Result.TABLE_NAME FROM (
  SELECT  TABLE_NAME,COLUMN_NAME,COUNT(*) AS QTA FROM INFORMATION_SCHEMA.COLUMNS  
  where  TABLE_SCHEMA = 'NAME_DB'
  and COLUMN_NAME IN ('Name','Price','Id')
  GROUP BY TABLE_NAME
 ) as Result
WHERE Result.QTA = 3

i have already tried to do without php 我已经尝试过不用php

Replace NAME_DB with your Database. 用您的数据库替换NAME_DB。

You would first need to know the tables in which it's possible to have the entry. 您首先需要知道可以在其中包含条目的表。 Use a loop to iterate over those tables and run the query, each time returning a result set and testing if records exist in the result set. 使用循环遍历这些表并运行查询,每次返回结果集并测试结果集中是否存在记录。 This will tell you what tables have the entry. 这将告诉您哪些表具有该条目。

General Approach: 一般的做法:

$array = array("table1", "table2", "table3", "table4", "table5");
foreach($array as $table) {
    //build your query using the table name
    $query = "SELECT something FROM " .  $table;
    //exec your query against your db and return results
    //test if records exist in result set.  If true, you know the table name based on the loop iteration ($table).
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM