dousong1926 2013-12-29 13:18
浏览 25
已采纳

从第2和第3个表中获取第1个表中匹配值的值

I am a jQuery developer and I do not have good idea on how to retrieve data from tables. I am just trying to learn it.

I have a special case to deal with. Consider three tables

tb1 
-----------------------------------------------
    pid    fname     lname       cid       eid
    12      jo         mo        16345     2345
    13      ko         ro        16324     2435

tb2
-----------------------------------------------
    cid     cname
   16345    amazed
   16324    bored

tb3
------------------------------------------------
    eid      ename
    2345      nolo
    21345     johny

I want to retrieve the data for the matching pid value. Say,

select * from tb1 where pid = 12 

It returns me pid, fname, lname, cid, eid

The cid value is 16345, Instead the number. I want that cid value to be matched to the tb2 and get the cname column value that is amazed and same with the eid that is the ename : nolo I want those numbers to be matched to tb2 and tb3 and get their string values.

I could do it using 3 MySQL queries

This is what I have tried

 $result = mysql_query("select * from tb1 where pid = 12");
 $row = mysql_fetch_array($result,MYSQL_ASSOC);
 $cname = mysql_query("select cname from tb2 where cid = '$row[cid]'");
 $x =  mysql_fetch_array($cname,MYSQL_ASSOC);
 $cname = mysql_query("select ename from tb3 where eid = '$row[eid]'"); 
 $y =  mysql_fetch_array($cname,MYSQL_ASSOC);

But I feel the code is not ideal. I guess there must be a way to retrieve in a single query but I am not sure what it must be. Maybe joins or sub-queries.

  • 写回答

2条回答 默认 最新

  • dongshan7060 2013-12-29 13:23
    关注

    Use joins on 3 tables

    SELECT tb1.*, tb2.cname, tb3.ename from tb1
    JOIN tb2 ON tb1.cid = tb2.cid
    JOIN tb3 ON tb1.eid = tb3.eid
    WHERE tb1.pid = 12
    

    Hope this helps

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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line