[英]MySQL subquery from another database where table name depends on main query
Hi I am trying to sub query a table(name: table_guest_id) from another database where id from the table name depends on the main query. 您好我正在尝试从另一个数据库子查询表(名称:table_guest_id),其中表名中的id取决于主查询。 Here is the set up of my databases:
这是我的数据库的设置:
And this is my sql code: 这是我的sql代码:
public function getListAttendee($user)
{
$sql = "SELECT p.name e.user, e.ID, e.date
FROM events e, profile p
WHERE p.user_id=e.user AND e.event_date >= CURDATE()
AND (SELECT COUNT(*)
FROM dbName.table_guest_[??note: need to insert e.ID??] a
WHERE a.event_id=e.ID AND a.user_id='{$user}' AND
a.status='invited') > 0";
}
I have put a note where ID OR e.ID will be inserted, but it is not working yet. 我已经添加了一个注释,其中将插入ID OR e.ID,但它还没有工作。 Please let me know if you have a different solution on how to sub query a table where the name of the table depends on the main query values.
如果您对如何子表查询表的名称取决于主查询值的表有不同的解决方案,请告诉我。 IS THIS IDEA EVEN POSSIBLE?
这个想法有可能吗?
It seems you are trying to perform variable substitution on a SQL table name. 您似乎正在尝试对SQL表名执行变量替换。
FROM dbName.table_guest_[??note: need to insert e.ID??] a
You Can't Do That™ directly in SQL. 你不能直接在SQL中做到这一点。 You'll need to write your php code to generate that table name, or use the string-processing feature that the MySQL team calls prepared statements.
您需要编写PHP代码来生成该表名,或者使用MySQL团队调用预处理语句的字符串处理功能。
If your different databases are hosted on the same MySQL server, you can write queries that refer to more than one of them at a time. 如果您的不同数据库托管在同一MySQL服务器上,则可以一次编写引用多个数据库的查询。 Simply give the database name as well as the table name.
只需提供数据库名称和表名称即可。 For example, if you have databases
db1
and db2
you can do this. 例如,如果您有数据库
db1
和db2
,则可以执行此操作。
SELECT whatever
FROM db1.events e
JOIN db2.user_118 u ON whatever = whatever
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.