我有两个表customer
和customer_transaction
。两者都有共同的 customer_id
,但 customer_transaction
还有一个字段 description,我希望根据共同的 customer_id 与结果一起返回该字段。
结果工作正常,但对于不同时具有 customer_id 和 customer_transaction 的所有记录,省略 customer_id。根据图像描述。我确信我在这里遗漏了一些小东西。
相关代码的一部分。我似乎认为问题出在 SELECT 语句上。
$sql = "SELECT * FROM customer LEFT OUTER JOIN customer_transaction ON customer. customer_id =customer_transaction. customer_id WHERE customer.customer_group_id = $input";
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$phpvar = "$row[description] "; //creat variable for descriptio so as to limit the length using substr
echo '<tr>';
echo '<td>'. $row['customer_id'] . '</td>';
echo '<td>'. $row['company_name'] . '</td>';
echo '<td>'. $row['firstname'] ." ". $row['lastname'] .'</td>';
echo '<td>'. $row['email'] . '</td>';
echo '<td>'. $row['telephone'] . '</td>';
echo '<td>'. $row['customer_id'] . '</td>';
echo '<td>'. $row['customer_group_id'] . '</td>';
echo '<td>'. substr($phpvar,0) . '</td>'; //Limit the length of the transactions here
echo '<td width=250>';
最佳答案
问题是您有两次 customer_id。然而,该数组只能有一个名为 customer_id
的键。使用字段名称作为键,将值逐个字段复制到数组中。第二次出现的值(来自 customer_transaction 表的值)将覆盖来自 customer 表的值,并且由于并非每个客户都有交易,因此您将在其中看到空字段。
最好的解决方案是在您需要的领域更加精确。无论如何,只获取您需要的字段而不是使用 *
是一个很好的做法。
因此,您的查询可能如下所示。稍微详细一点,但可以灵活地使用别名、计算值,并且没有返回不使用的字段的开销。
SELECT
c.customer_id,
c.company_name,
c.firstname,
c.email,
c.telephone,
/* You could provide the field with an alias */
t.customer_id as transaction_customer_id,
/* Or use its value to return a more sensible value */
CASE WHEN t.customer_id IS NULL
THEN 'N'
ELSE 'Y' END AS has_transaction,
t.customer_group_id
FROM customer
LEFT OUTER JOIN customer_transaction ON customer. customer_id = customer_transaction.customer_id
WHERE customer.customer_group_id = $input
关于PHP MYSQL SELECT AND LEFT JOIN - 不返回所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45815237/