如何通过id从2个表中选择数据

时间:2012-12-06 17:26:27

标签: sql xml export

我有一个脚本从表中获取数据并导出到xml,但我需要从2个不同的表中获取数据。

Table 1: Products

i have inside:

id code

Table 2: Stock

i have inside

id qty

我的脚本是:

<?php
    $db_host = "localhost";

    $db_name = "test";
    $db_username = "root";
    $db_password = "";

    $dbh = mysql_connect($db_host, $db_username, $db_password) or die("Unable to connect to MySQL");
    mysql_query('SET NAMES "utf8"');
    mysql_select_db($db_name, $dbh) or die("Could not select $db_name");

    $sql = "select * from products ";

    $q = mysql_query($sql);
    $custom = '"';

    $xml = "\n";
    $xml .= "<XML>\n";
    while($r = mysql_fetch_assoc($q))
    {

        $xml .= "   <PRODUCT code=$custom " . $r["code"] . "$cusmot qty=$custom " . $r["qty"] . "$custom />\n";

    }
    $xml .= "</XML>";

    header("Content-type: text/xml");
    echo $xml;
?>

需要帮助才能根据产品表上的ID从Stock结果中获取数量。

欢迎任何帮助。

3 个答案:

答案 0 :(得分:1)

SELECT p.id, p.code, s.qty
FROM products p
INNER JOIN stock s ON p.id = s.id

答案 1 :(得分:1)

尝试更改SQL以从两个表中提取数据:select p.code, s.qty from products p, stock s where p.id = s.id。通过这种改变,您的PHP几乎(或完全)可以工作!

答案 2 :(得分:0)

您应该使用此查询而不是代码中存在的查询:

SELECT p.id, p.code, s.qty
FROM product p, stock s
WHERE p.id = s.id