COUNT(*) AS count FROM `comments` WHERE `user_id` = ?' ).execute( user[:id] ).first[:count] ↓↓↓ # プリペアドステートメント無効 comment_count = db.xquery( 'SELECT COUNT(*) AS count FROM `comments` WHERE `user_id` = ?', user[:id] ).first[:count]
* FROM `comments` WHERE `post_id` = '12601' ORDER BY `created_at` DESC LIMIT 3\G SELECT * FROM `users` WHERE `id` = '533'\G SELECT COUNT(*) AS `count` FROM `comments` WHERE `post_id` = '9995'\G def make_posts(results) results.to_a.each do |post| post[:comment_count] = db.xquery('SELECT COUNT(*) FROM comments WHERE post_id = ?') comments = db.xquery('SELECT * FROM `comments` WHERE `post_id` = ? )
p.id, p.user_id, p.body, p.created_at, p.mime, u.account_name FROM `posts` AS p JOIN `users` AS u ON (p.user_id=u.id) WHERE `user_id` = '66' AND u.del_flg=0 ORDER BY p.created_at DESC LIMIT 20\G
p.id, p.user_id, p.body, p.created_at, p.mime, u.account_name -> FROM `posts` AS p JOIN `users` AS u ON (p.user_id=u.id) -> WHERE `user_id` = '66' AND u.del_flg=0 -> ORDER BY p.created_at DESC -> LIMIT 20\G *************************** 1. row *************************** id: 5077 user_id: 66 body: Bye ((ヾ( ^-^)ゞ Byeー♪ created_at: 2016-01-02 10:24:37 mime: image/jpeg account_name: janice ~中略~~ 6 rows in set (0.06 sec)
p.created_at, p.mime, u.account_name FROM `posts` AS p JOIN `users` AS u ON (p.user_id=u.id) WHERE `user_id` = '66' AND u.del_flg=0 ORDER BY p.created_at DESC LIMIT 20\G *************************** 1. row *************************** ~中略~ *************************** 2. row *************************** id: 1 select_type: SIMPLE table: p partitions: NULL type: index possible_keys: NULL key: posts_order_idx key_len: 4 ref: NULL rows: 20 filtered: 1.00 Extra: Using where 2 rows in set, 1 warning (0.00 sec) mysql> explain SELECT p.id, p.user_id, p.body, p.created_at, p.mime, u.account_name FROM `posts` AS p JOIN `users` AS u ON (p.user_id=u.id) WHERE `user_id` = '66' AND u.del_flg=0 ORDER BY p.created_at DESC LIMIT 20\G *************************** 1. row *************************** ~中略~ *************************** 2. row *************************** id: 1 select_type: SIMPLE table: p partitions: NULL type: ref possible_keys: posts_user_index key: posts_user_index key_len: 4 ref: const rows: 6 filtered: 100.00 Extra: Using index condition 2 rows in set, 1 warning (0.00 sec) →
p.body, p.created_at, p.mime, u.account_name FROM `posts` AS p FORCE INDEX (posts_user_index) JOIN `users` AS u ON (p.user_id=u.id) WHERE `user_id` = '66' AND u.del_flg=0 ORDER BY p.created_at DESC LIMIT 20\G