Site icon บริษัท โค๊ดบี จำกัด

MySQL วิธี select ข้อมูล แบบ random แถวข้อมูล

MySQL-วิธี-select-ข้อมูลแบบ-random-แถวข้อมูล

MySQL-วิธี-select-ข้อมูลแบบ-random-แถวข้อมูล

&NewLine;<p class&equals;"wp-block-paragraph">ในคำสั่ง MySQL วิธี select ข้อมูล กรณีที่เราต้องการ select หรือดึงข้อมูลขึ้นมาแสดงผล แบบให้มีการแรนดอม ไม่ต้องจัดเรียงข้อมูล เราสามารถใช้คำสั่ง rand&lpar;&rpar; ในส่วนของ order by ได้<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">ตัวอย่งเช่น เราต้องการดึงข้อมูลร้านค้า จำนวน 10 ร้านขึ้นมาแสดงผล โดยไม่ต้องการให้เรียงร้านตามข้อมูลใด ๆ สามารถเขียนคำสั่งได้ดังนี้<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code lang&equals;"sql" class&equals;"language-sql">SELECT store&lowbar;name FROM store ORDER BY rand&lpar;&rpar; LIMIT 10<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">หรืออีกวิธีหนึ่ง กรณีที่เราต้องการดึงข้อมูลร้านค้าจำนวน 10 ร้านค้าขึ้นมาแสดง โดยร้านค้าทั้ง 10 ร้านนั้น ต้องเป็นร้านค้าล่าสุด แต่ไม่ต้องการให้เรียงลำดับตามวันเวลาเปิดร้าน ก็ใช้คำสั่ง shuffle ใน PHP เข้ามาช่วย แทนที่จะใช้คำสั่ง rand&lpar;&rpar; ใน MySQL ตัวอย่างเช่น<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code lang&equals;"php" class&equals;"language-php">&dollar;sql &equals; "SELECT store&lowbar;name FROM store ORDER BY timestamp DESC LIMIT 10"&semi;&NewLine;&dollar;result &equals; &dollar;conn-&gt&semi;query&lpar;&dollar;sql&rpar;&semi;&NewLine;shuffle&lpar;&dollar;result&rpar;&semi;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">เริ่มต้นคือ select ข้อมูลขึ้นมา 10 row ก่อน โดยให้เรียงจากวันเวลาล่าสุดที่เพิ่มข้อมูลเข้าไป จากนั้นใช้คำสั่ง shuffle ในการแรนดอมการจัดเรียงตำแหน่งของข้อมูลภายใน Array <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">ผลลัพธ์ที่ได้คือ ข้อมูลที่แสดงผลทุกครั้ง จะมาจากข้อมูล 10 row ล่าสุด แต่มีตำแหน่งของข้อมูลที่ไม่เหมือนกันทุกครั้ง<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">สำหรับใน codeigniter framework เราสามารถเขียนได้ดังนี้ครับ<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code lang&equals;"php" class&equals;"language-php">&dollar;this->db->select&lpar;"store&lowbar;name"&rpar;&semi;&NewLine;&dollar;this->db->from&lpar;"store"&rpar;&semi;&NewLine;&dollar;this->db->order&lowbar;by&lpar;"rand&lpar;&rpar;"&rpar;&semi;&NewLine;&dollar;this->db->limit&lpar;10&rpar;&semi;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"><&sol;p>&NewLine;

Exit mobile version