简体   繁体   English

动态选择哪个表

[英]Dynamically choose which table

I want to have the query dynamically choose which table it looks up against based on a value in a particular row in another table. 我想让查询动态地根据另一个表中特定行中的值选择要查找的表。

I have this query: 我有这个查询:

SELECT d.name

FROM `database1`.domains AS d
WHERE (SELECT COUNT(u.id) FROM <<d.db_name>>.users u) > 0

I want to use the value of d.db_name as database name. 我想使用d.db_name的值作为数据库名称。 Example: d.db_name = database2 示例:d.db_name = database2

i want this: 我要这个:

SELECT d.name

FROM `database1`.domains AS d
WHERE (SELECT COUNT(u.id) FROM `database2`.users u) > 0

You could use variables for this: 您可以为此使用变量:

SET @table_name = "some_table";

SELECT * FROM @table_name;

If you want to change the variable value depending on the results of your select you coudl use IF like this: 如果要根据选择的结果更改变量值,则可以使用IF,如下所示:

IF(some_column>50, @table_name := "value for true", @table_name := "value for false");

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

相关问题 MySQL如何在创建视图时动态选择从哪个表获取数据 - MySQL How to dynamically choose which table to get data from when creating a view 在php post中选择要更新的mysql表 - Choose which mysql table to update in php post 解释在JOIN语句中选择“FROM”的表 - Explain which table to choose “FROM” in a JOIN statement 如何动态选择要指向的 MySQL 服务器? - How can I dynamically choose which MySQL server to point to? 如何从A表中选择B表中不存在的值? - How to choose values from A table which are absent in B table? 在运行时动态选择表名的最佳方法是什么? - What's the best way to choose a table name dynamically at runtime? Spring Boot:如何使用多个模式并动态选择在运行时使用哪个模式 - Spring Boot: How to use multiple schemas and dynamically choose which one to use at runtime MySQL:是否可以根据第三个表中的字段值选择要从哪个表中选择? - MySQL: Can you choose which table to select from based on the value of a field in a third table? PHP 如何选择要显示的表格,然后在提交表单后保持该表格显示 - PHP How to choose which table to display and then keep that table displayed after a form submission 在MySQL中选择哪个引擎 - Which engine to choose in MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM