简体   繁体   English

使用联接和条件选择MYSQL动态表名称

[英]MYSQL dynamic table name select with join and criteria

If I have this schema 如果我有这个架构

  • lists ( lead_id , list_id, campaign_id, ...) 列表( lead_id ,list_id,campaign_id等)
  • campaign (campaign_id, ...) 广告活动(campaign_id,...)
  • custom_list_id (lead_id, ...) custom_list_id(lead_id,...)

there are many tables with name custom_ list_id for various list_id s and I want to: 有许多名为custom_ list_id表,用于各种list_id ,我想:

SELECT * from lists ls inner join campaign c ON c.id=ls.campaign_id
inner join custom_"@LISTID" cll ON ls.lead_id = cll.lead_id

How do I write this query? 如何编写此查询? thnx n

Not sure what sql you really want, but try this: 不知道您真正想要什么SQL,但是请尝试以下操作:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'INNER JOIN custom_',  list_id, 'cll', list_id, ' ON ls.lead_id = cll', list_id '.lead_id')
    )
    SEPARATOR ' '
  ) INTO @sql
FROM lists ;
SET @sql = CONCAT('SELECT * from lists ls inner join campaign c ON c.id=ls.campaign_id ', @sql);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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

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