1

MySQL に (そして PHP を使用して) 以下のような 2 つのテーブルがあります。

------------------------       
|                      |
|        sizes         |   <--- This table is what populates the Select Box
|                      |
------------------------
|    id     |   name   |
|           |          |           
|     1     |   Small  |
|     2     |   Medium |
|     3     |   Large  |
------------------------

----------------------------------------       
|                                      |
|            user_entries              | <--- This table relates to above by "size_id"
|                                      |
----------------------------------------
|    id     |   user_id  |   size_id   |
|           |            |             |
|     1     |     25     |      2      |
|     2     |     12     |      3      |
|     3     |     15     |      3      |
----------------------------------------

私の質問は次のとおりです。選択ボックスにすべてのサイズ オプション (Small、Med、Large) を入力し、ユーザーの好みに基づいてオプションを事前に選択する SELECT ステートメントを作成するにはどうすればよいですか。

たとえば、user_id=25 のユーザーの場合、HTML は次のようになります。

<select>
   <option>Small</option>
   <option selected="selected">Medium</option>
   <option>Large</option>
</select>
4

2 に答える 2

2

SQL は次のとおりです。

SELECT s.id, s.name, ue.id as UserSelected
  FROM sizes s
    LEFT JOIN user_entries ue ON s.id=ue.size_id AND ue.user_id=XXX
  ORDER BY s.id 

(順番はお好みで)

結果を実行すると、「UserSelected」が NULL でない (つまり、値がある) 場合、選択されたエントリがあります。


SQL のヒント: テーブル間で列名を同じにして、"size_id" がサイズ テーブルの id フィールドの名前であり、user_entries テーブルの外部キーになるようにしてください。このようにすると、問題を引き起こす 2 つの「id」列がこのクエリに含まれなくなります。

また、常に user_id に基づいて検索/更新するため、user_entries テーブルの「id」列はおそらく必要ありませんか? 必要がない場合は、処理する列/インデックスが 1 つ少なくなります。

于 2012-07-19T02:43:20.317 に答える
1
// get size id from user entries table based on user id
$result2= mysql_query("SELECT size_id from user_entries where user_id='$user_id'");
$row2 = mysql_fetch_assoc($result2);
$sel_size_id =$row2['size_id'];

//dropdownlist query
$query="SELECT name,id FROM sizes";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);

//populate the dropdownlist
while($row = mysql_fetch_assoc($result)) { 
      //determine if the size id is selected
      $selected = ($row['size_id '] == $sel_size_id ) ? ' selected="selected" ' : NULL;
      echo  '<option value="' . $row['size_id']. '"' . $selected . '>'.$row['name'].'</option>\n';
}
于 2012-07-19T02:44:13.450 に答える