dshmkgq558192365 2013-10-11 03:10
浏览 76

PHP + Mysql:来自第一个查询的动态表名,用于执行第二个查询

I have three tables, the first is a table storing applications, the second is a table storing different online forms (different types of applications), the third is a table that stores actual form data:

    TABLE applications=========
    -applicationID (PK)
    -formID (FK)
    -formRecordID
    ====================  

    TABLE forms=========
    -formID (PK)
    -formName
    -tableName (could be 'form_businessLicense','eventLicense',etc)
    ====================

    TABLE form_businessLicense=====
    -recordID (PK)
    -dateSubmitted
    -(a whole bunch of other data)
    ===============================

"formRecordID" points to "recordID" in "form_businessLicense" or "eventLicense". Since it could reference any table, it can't be a foreign key. So instead I grab the tableName from the "forms" table, then build a query to get all the application data from, say "form_businessLicense".

So I need to get data from, say, all applications plus a bit of data from the application form filled out (ex:form_businessLicense). I'm just going to paste my code (I'm actually querying all applications in a given set of IDs):

$applications = $this->selectAll(
            "SELECT applicationID, formName, tableName, fieldIdentifier, formRecordID, dateSubmitted, DATE_FORMAT(dateSubmitted,'%c/%e/%Y') AS dateSubmittedFormat
            FROM applications AS a 
            JOIN forms AS f
            ON a.formID = f.formID
            WHERE a.applicationID IN (".$applicationIDs.")
            ORDER BY dateSubmitted ASC"
        );

        for($a=0;$a<count($applications);$a++){
            $form = $this->select("SELECT ".$applications[$a]['fieldIdentifier']." AS identifierName
                FROM ".$applications[$a]['tableName']."
                WHERE recordID = ".$applications[$a]['formRecordID']
            );
            $applications[$a]['identifierName'] = $form['identifierName'];
        }

Is there any way to merge these two queries into one so I don't have to loop over all results and run a separate query for each result? I feel like I could maybe do this with a JOIN but I'm not sure how to reference the "tableName" and "formRecordID" for use in the same SQL statement.

  • 写回答

1条回答 默认 最新

  • dsgrgaz321973284 2013-10-21 11:15
    关注

    You need to apply join to three tables, and select count(PK) of third table while adding a group by clause for the PK of third table.

    Note: PK used for Primary Key

    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线