LEFT JOIN - 排序和分组

LEFT JOIN - Sort and Group

我只得到一行元素和匹配的类别。

$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


这是我的 table 结构:

+------------------------+
| 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 } ?>

只需向左 <-> 向右切换表格:

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>';