dongtiao0657 2012-03-26 08:45
浏览 36
已采纳

在php或MYSQL中分析DATA?

I've a table with more than 5000 rows. Each row has a category, and I want to use these rows in my program. The problem is do I analyze these rows each time inside classes ? Or get only the class need each time, and make each class decide which data to use. I know my explanation is a mess, but look at these to examples.

    PEOPLE
    --
    ID      NAME            CAT     AGE
    ------------------------------------
    1       Brad             5      23
    2       Goy              3      19
    2       Romeo            5      34
    2       Deborah          5      40
    ..      ..          ..      
    5000    Bob              1      56

now I want only to analayze the rows with cat = 5 and each row will be an object.

    First Solution 

    SELECT * FROM people Where CAT = 5
    and then in php make each class analyze the all data ? 

    foreach($people as $p)
    {
        if($p['age'] == 20)
        do......
    }

    Second solution
    in each class put a function to get the data

    function get_data
    {
        $query = 'SELECT * FROM people WHERE cat = 5 AND age = '.$this->age.'';
        then do....
    }

I HAVE A LOT OF ROWS 5000 it's an example, please help me and give me the more efficent solution the first one will hit the databse once but the same array will loop in each class (not good) the second will hit the database many times but will bring the indeed needed data.

  • 写回答

3条回答 默认 最新

  • drruhc4944 2012-03-26 08:53
    关注

    With no details given, the answer is certainly to filter data with the SQL query for many reasons. There are some situations though when db-level processing is not possible (e.g. when more complicated business logic is involved) but generally you should always try to filter data before it gets into your high-level code.

    That's precisely the job databases were invented for.

    In your example, collect all your ages in an array first and then run the following query:

    $sql = 'SELECT * FROM people WHERE cat = 5 AND age IN (' . implode(',', $ages) . ')';
    

    If you're using MySQL, the allowed size of IN sets is huge (32 Mb by default) which should be enough.

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

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行