来自2表的mysql数据

时间:2014-06-11 08:12:23

标签: php mysql

是的,现在我知道JOIN,但仍然没有解决这个问题。

  

$ gender = 6;

     

$ result = mysqli_query($ con," SELECT * FROM ps_customer c LEFT JOIN   ps_adress a ON a.customer_id = c.customer_id WHERE   c.id_gender =' $性别'&#34);

     

的var_dump($结果);

     

mysqli_close($ CON);

这是我的代码,但结果为:

我尝试了var_dump来检查为什么我无法打印数据。

我的代码的数据打印是否正确?

 echo "<h1>People</h1>";
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th>Company</th>
<th>Phone</th>
</tr>";



$result = mysql_query($query) or die(mysql_error());
echo var_dump($result);
while($row = mysql_fetch_array($result)){
  echo "<tr>";
  echo "<td>" . $row['id_customer'] . "</td>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['email'] . "</td>";
  echo "<td>" . $row['company'] . "</td>";
  echo "<td>" . $row['mobile_phone'] . "</td>";
  echo "</tr>";
}

4 个答案:

答案 0 :(得分:0)

简单加入即可。

SELECT *
FROM ps_customer c
    LEFT JOIN ps_address a ON a.customer_id=c.customer_id
WHERE c.id_gender = '$gender'

答案 1 :(得分:0)

SELECT *
FROM adress a
INNER JOIN customer c ON a.customer_id = c.id
WHERE c.id_gender = $gender

答案 2 :(得分:0)

您需要LEFT JOIN(如果客户没有地址记录)。 假设两个表都具有相同的列名称&#34; customer_id&#34;识别客户,您可以使用:

SELECT ps_customer.name,
       ps_customer.lastname,
       ps_customer.company,
       ps_address.phone,
       ps_address.mobile
FROM ps_customer
LEFT JOIN ps_address ON ps_address.customer_id = ps_customer.customer_id
WHERE ps_customer.id_gender = '$gender'

但要小心点。如果每个客户有多个地址记录,您将获得包含每个地址记录的相同客户数据的多行。如果是这种情况,则需要更复杂的查询:)

答案 3 :(得分:0)

您的查询应该是

"select cus.name, cus.lastname, cus.company from ps_customer cus, ps_address add where id_gender='".$gender."' and cus.customer_id=add.customer_id"