显示两个表的相对数据

时间:2014-06-16 09:53:16

标签: php mysql sql

我的php和mysql编码有问题我有两张桌子

表1:haz

haz_id  |  haz_description  
-------------------------
   1    |     Good

   2    |     Bad

   3    |     Great

表2:风险

risk_assessment_id | haz_id | haz_id_2 | haz_id_3
-------------------------------------------------
   SF-050-PRE      |   3    |    1     |    2

我想将它们结合起来,以便我可以在风险表中获得每种危害的描述

我不知道如何解决这个问题我已经尝试了一切,但我似乎无法获取数据,我无法确定问题是来自我的加入还是来自代码的回声部分。

到目前为止

代码:

> $sql=SELECT risk_assessment.haz_no_id AS risk_assessment.haz_no_id,
              risk_assessment.haz_no_id_2 haz_no_id.haz_no_id AS haz_no_id.haz_no_id,
              haz_no_id.haz_description FROM risk_assessment, 
              haz_no_info 
              WHERE (risk_assessment.haz_no_id = haz_no_info.haz_no_id) 

这是代码的输出部分

> $result=mysql_query($sql); 
  while ($row = mysql_fetch_assoc($result)) { 
       echo $row['ops_id']. 
            $row['haz_no_id'].' '.
            $row['haz_description']. 
            $row['haz_no_id_2'].' '.
            $row['haz_description'];
  }

如果有人能提供帮助,那就太棒了

谢谢

4 个答案:

答案 0 :(得分:0)

SELECT risk_assessment.haz_no_id, 
       haz_no_id.haz_description as haz_id
FROM risk_assessment, haz_no_info 
WHERE (risk_assessment.haz_no_id = haz_no_info.haz_no_id) 
ORDER BY risk_assessment.haz_no_id DESC

答案 1 :(得分:0)

使用三个连接:

SELECT ra.haz_no_id, h1.haz_description, h2.haz_description, h3.haz_description
       haz_no_id.haz_description as haz_id
FROM risk_assessment ra left join
     haz_no_info h1
     on ra.haz_id1 = h1.haz_id left join
     haz_no_info h2
     on ra.haz_id3 = h2.haz_id left join
     haz_no_info h3
     on ra.haz_id3 = h3.haz_id;

如果某些描述不匹配,则left join

答案 2 :(得分:0)

我想你想做的是这样的事情:

DEMO:http://sqlfiddle.com/#!2/60e686/9

$sql = "SELECT risk_assessment_id, h1.haz_description AS d1, " .
" h2.haz_description AS d2, " .
" h3.haz_description AS d3 " .
" FROM risk LEFT JOIN haz h1 ON risk.haz_id = h1.haz_id" .
" LEFT JOIN haz h2 ON risk.haz_id_2 = h2.haz_id" .
" LEFT JOIN haz h3 ON risk.haz_id_3 = h3.haz_id;";

希望这有帮助。

答案 3 :(得分:0)

非常简单只需使用别名名称并连接表三次

 SELECT risk.risk_assessment_id as risk_id, risk.haz_id as haz_id_one, risk.haz_id_2 as      haz_id_two, risk.haz_id_3 as haz_id_three, one.haz_description as one_desc, two.haz_description as two_desc, three.haz_description as three_desc FROM risk 
LEFT JOIN haz as one ON one.haz_id = risk.haz_id
LEFT JOIN haz as two ON two.haz_id = risk.haz_id_2
LEFT JOIN haz as three ON three.haz_id = risk.haz_id_3