SELECTING multiple rows by 2 columns

前端 未结 1 1961
借酒劲吻你
借酒劲吻你 2021-01-27 22:04
  [         POSTS         ]
  | id |   title  | class |
  |----|----------|-------|
  | 1  |   4567   |    2  |
  | 2  |   1234   |    1  |
  | 3  |   9124   |    1  |
          


        
相关标签:
1条回答
  • 2021-01-27 22:30

    I think you are looking for

    SELECT * FROM Posts WHERE class in (1,2,'w') ORDER BY class ASC
    

    This will give you all the posts with the class values within the In () statement. It will show each record separately which means you will have two rows for titles which have multiple class values. Since it looks like you want to separate them using PHP that should be ok. Then you can do that in your while loop like:

    $classes = array();
    while($row = $stmt->fetch()){
      if(!isset($classes[$row['class']])){ $classes[$row['class']] = array(); }
      $classes[$row['class']][] = $row['title'];
    }
    

    This would give you arrays of Titles for each class:

    [
       1=>[1234,9124]
       2=>[4567]
       'w'=>[9124]
    ]
    

    Then you can output them all in order of the class or by class:

    foreach($classes as $key => $class){
       echo "Class Value: ".$key; // just to show the order
       foreach($class as $title){ echo "<a>".$title."</a>"; }
    }
    

    Which will wind up giving you:

    Class Value: 1
    <a>1234</a>
    <a>9124</a>
    Class Value: 2
    <a>4567</a>
    Class Value: w
    <a>9124</a>
    

    I am not entirely sure if this leads you to what you are looking for, however, it does give you a workflow to be able to order the posts by class and output them based on class. I hope this helps

    0 讨论(0)
提交回复
热议问题