内部连接2个表,并在while期间获取结果

时间:2013-07-01 20:28:26

标签: php mysql join

我做了这个查询,所以它将2个表合并为一个,这样它就可以获得办公室和保险公司的名称,而不是数字变量,但它不起作用。

$values = mysql_query("SELECT pat_id,pat_lname,pat_fname,pat_date,pat_loc,pat_ins,pat_show FROM patients INNER JOIN offices ON office_id = pat_loc INNER JOIN insurance ON ins_id = pat_ins ");

办公室数据库的外观如下:

http://i.stack.imgur.com/rXWYG.png

导出时的外观

http://i.stack.imgur.com/ienh4.png

我试图让它在出口时显示名称Hackensack,而不是pat_loc中的位置2。我怎样才能让它发挥作用?

以下是整个声明:

$values = mysql_query("SELECT pat_id,pat_lname,pat_fname,pat_date,pat_loc,pat_ins,pat_show FROM patients INNER JOIN offices ON office_id = pat_loc INNER JOIN insurance ON ins_id = pat_ins ");


while ($rowr = mysql_fetch_row($values)) {
for ($j = 0; $j < $i; $j++) {
    $csv_output .= $rowr[$j] . ", ";
}
$csv_output .= "\n";
} 

1 个答案:

答案 0 :(得分:1)

SELECT
  pat_id,
  pat_lname,
  pat_fname,
  pat_date,
  office_name,
  pat_ins,
  pat_show
FROM patients
INNER JOIN offices ON office_id = pat_loc
INNER JOIN insurance ON ins_id = pat_ins

更新:根据您在下面的评论,我想出了以下内容:

$result = mysql_query('
    SELECT
        pat_id AS `user_id`,
        pat_fname as `First Name`,
        pat_lname as `Last Name`,
        pat_date as `IME Date`,
        pat_loc as `Location`,
        pat_ins as `Insurance Company`,
        pat_show as `Show(Y/N)`
    FROM patients
    INNER JOIN offices ON office_id = pat_loc
    INNER JOIN insurance ON ins_id = pat_ins
');

$csv_output = '';
$headersPrinted = false;
while ($patient = mysql_fetch_assoc($result))
{
    if (!$headersPrinted)
    {
        $csv_output .= implode(',', array_keys($patient))."\n";
        $headersPrinted = true;
    }

    $csv_output .= implode(',', array_values($patient))."\n";
}

然而,有了这个,你加入officesinsurance表是没有明显用处的。我假设您想要从这些表中显示一些值来代替原始ID。在这种情况下,您可以在查询中将pat_loc替换为office_name