MYSQL动态表名选择带连接和条件

时间:2016-07-08 23:21:09

标签: mysql sql select join

如果我有这个架构

  • 列表( lead_id ,list_id,campaign_id,...)
  • 广告系列(campaign_id,...)
  • custom_list_id(lead_id,...)

对于各种 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

如何撰写此查询? 日Thnx

1 个答案:

答案 0 :(得分:0)

不确定你真正想要的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;