我只获得一行元素和匹配的类别。
$stmt = $conn->prepare("SELECT lt_category.id, lt_category.title, lt_category_elements.category_id, lt_category_elements.title as elementitle, lt_category_elements.text
FROM lt_category
LEFT JOIN lt_category_elements ON lt_category.id = lt_category_elements.category_id");
类别1
类别2
类别3
这是我的表结构:
+------------------------+
| lt_category_elements |
+------------------------+
| id |
| category_id |
| title |
| text |
| rel_code |
| created |
+------------------------+
+------------------------+
| lt_category |
+------------------------+
| id |
| title |
| text |
| rel_code |
| created |
+------------------------+
如何在单个类别下获取缺失的元素?
但我需要:
这是我的输出代码:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="playerrow">
<span class="category"><?php echo $row['title']; ?></span>
<span class="category"><?php echo $row['text']; ?></span>
</div>
<?php } ?>
答案 0 :(得分:2)
只需切换左表&lt; - &gt;右:
SELECT lt_category.title,
lt_category_elements.category_id,
lt_category_elements.title as elementitle,
lt_category_elements.text
FROM lt_category_elements
LEFT JOIN lt_category
ON lt_category.id = lt_category_elements.category_id
ORDER BY lt_category_elements.category_id, lt_category_elements.id
这是你的php输出:
$curCat = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($curCat !== $row['category_id']) {
if ($curCat !== '')
echo '</div>';
echo '<div class="playerrow">';
echo '<span class="category">'.$row['title'].'</span>';
}
echo '<span class="category">'.$row['text'].'</span>';
$curCat = $row['category_id'];
}
if ($curCat !== '')
echo '</div>';