dsnd7200 2019-02-27 18:07
浏览 77
已采纳

这个连接语句有什么问题?

I'm working with a MySQL server Server version: 5.6.42-cll-lve - MySQL Community Server (GPL) and I'm having some major issues with CONCAT()

       public function get_urls() {
        // Create query
        $query = "SELECT a.Name, a.PrimaryVersion, e1.URL
        FROM " . $this->table . " a
        INNER JOIN
        FunnelsFlows b ON a.Funnel_ID = b.Funnel_ID
        INNER JOIN
        BackendFlows c ON b.BackendFlow_ID = c.BackendFlow_ID
        INNER JOIN
        BackendLevels d ON CONCAT(c.Level, :lv) = d.BackendLevel_ID
        LEFT JOIN
        BackendPages e1 ON d.Upsell = e1.BackendPage_ID
        LEFT JOIN
        BackendPages e2 ON d.Downsell1 = e2.BackendPage_ID
        LEFT JOIN
        BackendPages e3 ON d.Downsell2 = e3.BackendPage_ID
        WHERE                    
        a.Funnel_ID = :fid 
        LIMIT 0,1";
        // Prepare statement
        $stmt = $this->conn->prepare($query);
        // Bind ID
        $stmt->bindParam(':fid', $this->fid, PDO::PARAM_INT);
        $stmt->bindValue(':lv', $this->lv, PDO::PARAM_STR);
        // Execute query
        $stmt->execute();

Running this code throws the following error: PHP Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'c.Level' in 'on clause' in ...

The entire database structure you can view here:
https://app.sqldbm.com/MySQL/Share/wBAF2JMRFFSoPPjIPdYZc0GFrngIE8md_DYjF4jNYw0

  • 写回答

3条回答 默认 最新

  • doujiang1993 2019-02-27 19:36
    关注

    Your query cannot work like that. You are trying to concat a field content CONCAT(c.Level, :lv) with a parameter :lv. This results in a string if there were a column Level. However, you rather want to build a dynamic column name like Level1 / Level2 aso.

    Unfortunately this cannot be done by parameters. This is owing to the fact, that query plans are prepared. Changing column names at execution time would alter the query plan.

    You either need to build dynamic SQL in such a case or write a complex ON clause.

    The ON clause:

    ON 
    (
      (:lv = 1 AND c.Level1 = d.BackendLevel_ID)
      OR
      (:lv = 2 AND c.Level2 = d.BackendLevel_ID)
      -- and so on
    )
    

    Dynamic SQL:

    $sql = 'ON (c.Level' . inval($this->lv) . ' = d.BackendLevel_ID)'
    

    Since PHP's intval function is considered to be safe, I would prefer the latter example in order to improve SQL performance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分