dongyingming8970 2016-09-05 16:54
浏览 69
已采纳

PHP / MySQL:如何从嵌套循环中区分重复的id

So, I have 2 tables and I am trying to get an output like this.

//output that i need
SCvalue 22
SCvalue 23
Cvalue  17
SCvalue 24
SCvalue 25
Cvalue  19

My tables, the key 16 have 2 sub value at my table 2 the SCvalue 22, 33 as well as the key 18.

TABLE_1
|  PID  | criteria_name  |
|   16  |    Cvalue 16   |      
|   17  |    Cvalue 17   |
|   18  |    Cvalue 18   |
|   19  |    Cvalue 19   |



TABLE_2
|   SID |  PID  |  Sub_criteria_name    |
|   22  |  16   |      SCvalue 22       |      
|   23  |  16   |      SCvalue 23       |
|   24  |  18   |      SCvalue 24       |
|   25  |  18   |      SCvalue 25       |

I used nested loop to get that output that i need but.

//the output giving to me duplicates the value
SCvalue 22
SCvalue 23
SCvalue 24 <-- need to remove
SCvalue 25 <-- need to remove
Cvalue  17
SCvalue 22 <-- need to remove
SCvalue 23 <-- need to remove
SCvalue 24
SCvalue 25
Cvalue  19

My fail query

$sql = mysql_query("SELECT * from TABLE_1 where PID NOT IN(SELECT PID from TABLE_2)");
while($row = mysql_fetch_assoc($sql)){

     $sql1 = mysql_query("SELECT distinct(SID), PID, Sub_criteria_name from TABLE_2");
     while($row2 = mysql_fetch_assoc($sql1)){
         echo $row2['Sub_criteria_name']."<br/>";
         echo $row['criteria_name']."<br/>";
     }
}
  • 写回答

1条回答 默认 最新

  • douhu4692 2016-09-05 17:00
    关注

    It seems like all you need is a single LEFT JOIN query:

    SELECT COALESCE(t2.Sub_criteria_name, t1.criteria_name)
    FROM Table1 AS t1
    LEFT JOIN Table2 AS t2 ON t1.PID = t2.PID
    ORDER BY t1.PID
    

    Demo here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题