doupu1949 2017-07-28 10:54
浏览 80
已采纳

内连接vs foreach循环性能

I'm trying to do something and I'm sure if I'm doing it in a right way. Let's say I have two tables in MySQL database with the following columns

-------------------------

Members
-------------------------
id        name      status
-----     -----     -----
1         Mike      0
2         Alex      0
3         John      1
4         Jack     -1

-------------------------

    Status
    -------------------------
    id        text
    -----     -----
   -1        disapproved
    0         reviewing
    1         approved

Now I need to display the information of the table "Members" in the following way:

id        name      status
-----     -----     -----
1         Mike      reviewing
2         Alex      reviewing
3         John      approved
4         Jack      disapproved

One way is to use an Inner Join between the two tables and the other way is to extract data from the "Members" table and put it inside a for-each loop and convert status values. In the latter way I don't need the "status" table at all.

I'm not sure which way is better. please let me know if you need more information to help me.

Thanks in advance.

Update

An for-each example for what I want to do is like this, supposing I have extracted data from "Memberes" table

foreach($data as $value)
    {
    if ($value['status'] == 0)
        $value['status'] = 'reviewing';
    if ($value['status'] == 1)
        $value['status'] = 'approved';      
    else
        $value['status'] = 'diapproved';        
    }
  • 写回答

2条回答 默认 最新

  • douziqian2871 2017-07-28 10:59
    关注

    In general, you absolutely want to be doing this via a join inside your MySQL database:

    SELECT
        t1.id, t1.name, t2.text AS status
    FROM Members t1
    INNER JOIN Status t2
        ON t1.status = t2.id
    

    The alternative of handling this inside your PHP code with a foreach loop is unattractive for several reasons. First, you would probably need to bring in all information from both tables, which is wasteful from both a memory and network usage point of view. Then, even after you have brought in the data, you would be relying on PHP to perform the join. PHP wasn't really designed for in house database operations, and cannot use something like an index to speed up the process.

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)