Mysql – where in clause order issue

MySQL

I'll admit, I'm an average query coder so I'm pretty sure my issue is "operator error"

I have 2 db tables. The columns are in ()

  • table1 (form_id, form_name, field_order)

  • table2 (field_id, field_name)

Table1 contains all my forms. The field_order column contains the ID's for all the field_names in table2. So the field_order column in table 1 looks like (682,1,2,341,72,72,73)

These numbers correspond to the id's for the fields in table 2.

Where my problem is, is that in my query using the IN clause, the form fields results are listed in ASC order by field_id in table2. I need the field_id and field_name to be listed in the field_order in table1.

Any help is appreciated. I think I'm missing something simple.

My code is below.

<?php   
$sqlForms = "select t1.form_id, t1.form_name, t1.field_ids from table1 as t1 where t1.form_id != '10' order by form_name asc";

$resultsSQL = $this->EE->db->query($sqlForms);
    if ($resultsSQL->num_rows() > 0)
    {
        echo "<table border=1>";

        foreach($resultsSQL->result() as $row)
        {
        echo "<tr>";
        echo "<td>".$row->form_id."</td><td>".$row->form_name."<br />";

        $formID = str_replace("|", ",", "$row->field_ids");

        $sqlFields = "select t2.field_id, t2.field_name
                        from table2 as t2
                        where t2.field_id IN (".$formID.")";

            $resultsFields = $this->EE->db->query($sqlFields);
                if ($resultsFields->num_rows() > 0)
                {
                    echo "<table border=2>";
                        foreach($resultsFields->result() as $rowFields)
                        {
                            echo "<tr><td>".$rowFields->field_id."</td><td>".$rowFields->field_name."</td></tr>";
                        }
                    echo "</table>";
                }

        echo "</td>";
        echo "</tr>";
        }
        echo "</table>";
    }
?>

Best Answer

I'm an idiot! All I needed to do was add ORDER BY FIELD(id,5,2,6,8,12,1...) to my code. I like it when the answer is an easy one. I just wish it wouldn't take me so long to figure out!