用pdo连接两个表

如何解决用pdo连接两个表

我想在数据库中联接两个表。它的“经典”方式效果很好,但是我的脚本中有很多选择查询,所以我想简化一下...

这是联合sql:

SELECT
    matches.id,matches.start_time,matches.category_id,matches.highl,first_team.tid,first_team.t_name,second_team.tid,second_team.t_name AS ft_name 
FROM matches 
    INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid 
    INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid 
ORDER BY matches.id DESC 
    LIMIT 10

我想要达到的目标是这样的,但是我不完全知道如何添加上面复制的所有值。

public function getMatches($table,$conditions = array()){
    $sql = 'SELECT ';
    $sql .= array_key_exists("select",$conditions)?$conditions['select']:'';
    $sql .= ' FROM '.$table;
    if(array_key_exists("where",$conditions)){
        $sql .= ' WHERE ';
        $i = 0;
        foreach($conditions['where'] as $key => $value){
            $pre = ($i > 0)?' AND ':'';
            $sql .= $pre.$key." = '".$value."'";
            $i++;
        }
    }

    if(array_key_exists("inner_join",$conditions)){
        $sql .= ' INNER JOIN '.$conditions['inner_join'];
    }

    if(array_key_exists("on",$conditions)){
        $sql .= ' ON '.$conditions['on'];
    }

    if(array_key_exists("as",$conditions)){
        $sql .= ' AS '.$conditions['as'];
    }

    if(array_key_exists("order_by",$conditions)){
        $sql .= ' ORDER BY '.$conditions['order_by'];
    }

    if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
        $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
    }elseif(!array_key_exists("start",$conditions)){
        $sql .= ' LIMIT '.$conditions['limit'];
    }

    $query = $this->db->prepare($sql);
    $query->execute();

    if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
        switch($conditions['return_type']){
            case 'count':
                $data = $query->rowCount();
            break;
            case 'single':
                $data = $query->fetch(PDO::FETCH_ASSOC);
            break;
            default:
                $data = '';
        }
    }else{
        if($query->rowCount() > 0){
            $data = $query->fetchAll();
        }
    }
    return !empty($data)?$data:false;
    }
}

以下是输出:

<div class="panel-heading">Matches</div>
    <table class="table">
        <tr>
          <th>#</th>
          <th>First Team</th>
          <th>Second Team</th>
          <th>Start Time</th>
        </tr>
        <?php
        include 'inc/functions.php';
        $db = new DB();
        $matches = $db->getMatches('matches',array('inner_join'=>'teams'),array('as'=>'first_team'),array('on'=>'matches.first_team_id = first_team.tid'),array('as'=>'second_team'),array('on'=>'matches.second_team_id = second_team.tid'),array('order_by'=>'matches.id'));
        if(!empty($matches)){ $count = 0; foreach($matches as $result){ $count++;?>
        <tr>
          <td><?php echo $count; ?></td>
          <td><?php echo $result['ft_name']; ?></td>
          <td><?php echo $result['t_name']; ?></td>
          <td><?php echo $result['start_time']; ?></td>
        </tr>
        <?php } }else{ ?>
        <tr><td colspan="4">No entry found!</td>
        <?php } ?>
    </table>
</div>

解决方法

老实说,对于我的一生,我永远都不会明白,PHP数组的墙是如何

array('inner_join'=>'teams'),array('as'=>'first_team'),array('on'=>'matches.first_team_id = first_team.tid'),array('inner_join'=>'teams'),array('as'=>'second_team'),array('on'=>'matches.second_team_id = second_team.tid'),array('order_by'=>'matches.id'));

甚至可以被认为比优雅紧凑的SQL“更短”

SELECT
    matches.id,matches.start_time,matches.category_id,matches.highl,first_team.tid,first_team.t_name,second_team.tid,second_team.t_name AS ft_name 
FROM matches 
    INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid 
    INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid 
ORDER BY matches.id DESC 
    LIMIT 10

更不用说意义和可读性了。

您是要节省自己输入一些SELECT或FROM这样的SQL关键字吗?认真吗用有意义且易于理解的SQL弄得一团糟真的值得吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-