LEFT JOIN - 排序和分组

时间:2015-02-24 16:22:19

标签: php mysql sorting left-join grouping

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

$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

  • element1(在那里)
  • 元素2,3,4,5(缺失)等。

类别2

  • element1(在那里)
  • 元素2,3,4,5(缺失)等。

类别3

  • element1(在那里)
  • 元素2,3,4,5(缺失)等。

这是我的表结构:

+------------------------+
| lt_category_elements   |
+------------------------+
| id                     |
| category_id            |
| title                  |
| text                   |
| rel_code               |
| created                |
+------------------------+

+------------------------+
| lt_category            |
+------------------------+
| id                     |
| title                  |
| text                   |
| rel_code               |
| created                |
+------------------------+

如何在单个类别下获取缺失的元素?

output

但我需要: enter image description here

这是我的输出代码:

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

1 个答案:

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