如果表1和2或3具有相同的ID,则显示名称

时间:2014-03-12 16:23:02

标签: php mysql

我有三张桌子:

  • 运动
  • 客户
  • 办公室

广告系列表一样,customer_id与客户表中的ID相同, 然后他必须在Customer表中显示customer_name。

现在,他正在显示客户ID:$row->customer_id

我现在有以下

if ($result = $mysqli->query("SELECT * FROM campaign ORDER BY campaign_id"))
{
    // display records if there are records to display
    if ($result->num_rows > 0)
    {
        // display records in a table
        echo "<table>";

        while ($row = $result->fetch_object())
        {
            // set up a row for each record
            echo "<tr>";
            echo "<td>" . $row->campaign_name . "</td>";
            echo "<td>" . $row->customer_id . "</td>";
            echo "<td>" . $row->office_id . "</td>";
            echo "</tr>";
        }

        echo "</table>";
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您提出的要求并不是很清楚,但也许可以尝试此查询?

SELECT c.*, cust.* FROM campaign c, customer cust WHERE c.customer_id=cust.customer_id ORDER BY c.campaign_id

使用显式(而不是隐式)JOIN,此查询可以写成:

SELECT c.*, cust.* FROM campaign c JOIN customers cust ON c.customer_id=cust.customer_id

作为备注,我通常更喜欢在查询中明确地调出列名,但由于您没有发布架构,因此我无法确定列的名称。可能是这样的:

SELECT c.campaign_name, cust.customer_id FROM campaign c JOIN customers cust ON c.customer_id=cust.customer_id