勉強会
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # SQL teamC ## 第1回SQL ### To Do 1. SELECTの使い方を調べる 2. 使い方に沿って記述する 3. デバッグしてみる 4. 確認 ### To Do 1. 問題1の回答をコピー 2. レコードの指定の仕方を調べる 3. 利用する 4. 確認 ### To Do 1. 問題1の回答をコピー 2. *をnameに変える 3. 利用する 4. 確認 ### To Do 1. 問題1の回答をコピー 2. レコードの指定方法を調べる 3. カラムの指定 4. 確認 ### To Do 1. 問題1の回答をコピー 2. 文字データで指定する方法を調べる 3. 確認 ### To Do 1. 問題5の回答をコピー 2. _aを削除 3. 確認 --- ## 第2回SQL ### To Do 1. アクセスログのテーブルのデータをもってくる 2. アクセスログID、郵便番号、都道府県、施設名、氏名のカラムを指定 3. 空ではないデータを取得方法を調べる 4. 郵便番号の空以外を指定 5. 確認 ### To Do 1. アクセスログID都道府県、氏名、エントリーページのカラムを指定 2. アクセスログのテーブルのデータをもってくる 3. 佐賀県かつエントリーページにlive400があるデータを指定 4. 確認 ### To Do 1. カラムの数の持ってき方を調べる 2. アクセスログのテーブルのデータをもってくる 4. 条件に合うものをカウントする 5. 確認 ### To Do 1. カラム全部表示 2. テーブル取得access_logs 3. 条件conference_info_idが29 4. 時間が早い順に並べ替え 5. 確認 ### To Do 1. 問題②をコピー 2. prefectureと都道府県の数を表示 3. テーブル取得access_logs 4. prefectureが「東京都」と「北海道」を指定 5. カラムの名前を分かりやすい名前に変更 6. 確認 SELECT prefecture , COUNT (*) FROM access_logs WHERE prefecture '%佐賀県%' AND entryPage LIKE '%live400%'; ### To Do 1. 問題⑤をコピー 2. prefectureと都道府県の数を表示 3. テーブル取得access_logs 4. prefectureの人数が40以上を指定 5. カラムの名前を分かりやすい名前に変更 6. 確認 --- ## 第3回SQL ### To Do 1. ER図調べる 2. access_logsとenquete_answersのデータを結合する方法を調べる 3. カラムをしていする 4. エイリアスを調べる 5. エイリアスを付与する 7. 確認 SELECT カラム名 FROM テーブル名 INNER JOIN テーブル名 ON 結合条件; SELECT id, name, status FROM users INNER JOIN contracts ON id = user_id; SELECT access_logs.accessLogID, access_logs.uid, access_logs.name, access_logs.created_at, enquete_answers.id,enquete_answers.uid AS uid2 FROM access_logs INNER JOIN enquete_answers ON access_logs.accessLogID = enquete_answers.access_log_id ; access_logs.accessLogID, access_logs.uid, access_logs.name, access_logs.created_at, enquete_answers.id,enquete_answers.uid AS uid2 ### To Do 1. inner_joinとアウタージョインの意味を調べる 2. access_logsを基準としてenquete_answers, user_listsを結合する。 3. カラムをしていする 4. エイリアスを全て付与する 5. 確認 SELECT access_logs.accessLogID AS A , access_logs.uid AS B , access_logs.name AS C , access_logs.created_at AS D , enquete_answers.id AS E , enquete_answers.uid AS uid2 , user_lists.userID AS userID , user_lists.userPassword AS userPassword FROM access_logs LEFT JOIN enquete_answers ON access_logs.accessLogID = enquete_answers.access_log_id LEFT JOIN user_lists ON access_logs.user_list_id = user_lists.userListId ; ### To Do 1. 2問目をコピー 2. access_logs user_listsのテーブルを結合する。 3. カラムをしていする 4. エイリアスを全て付与する 5. カンファレンス テスト25講演会のログを指定する。 6. IDとPWごとに表示する。 7. 表示する一番早いaccessTime 一番遅いstopTimeを指定する。 8. 確認 SELECT access_logs.conference_info_id AS AA , access_logs.accessLogID AS A , access_logs.uid AS B , access_logs.name AS C , min(access_logs.accessTime) AS CC , max(access_logs.stopTime) AS D , user_lists.userID AS userID , user_lists.userPassword AS userPassword FROM access_logs LEFT JOIN user_lists ON access_logs.user_list_id = user_lists.userListId WHERE access_logs.conference_info_id = 25 GROUP BY user_list_id ; ## 第4回SQL ### To Do 1.カラムを指定する(済み) 2.アクセスログを基準に結合されたアクセスログを表示(済み) 3.アンケートログのデータが無いものは非表示(済み) 4.複数のカラムを1つのカラムに結合する方法を調べる SELECT CONCAT(DEPT,ID),NAME FROM sample; 5.「テスト3講演会」のアクセスログを取得 SELECT access_logs.uid , CONCAT(access_logs.prefecture,access_logs.facility) AS CONCAT_pre_facility , access_logs.name , enquete_answers.answer1 , enquete_answers.answer2 , enquete_answers.answer3 , enquete_answers.answer4 , enquete_answers.answer5 FROM access_logs INNER JOIN enquete_answers ON access_logs.accessLogId = enquete_answers.access_log_id WHERE access_logs.conference_info_id = 3 ; ### To Do 1.カラムを指定する(都道府県、参加人数の平均、参加人数の合計を表示) 2.テーブルを指定する 3.テスト10講演会データを指定する 4.奈良と群馬を抽出 5.確認 https://www.softel.co.jp/blogs/tech/archives/2570 SELECT access_logs.prefecture , TRUNCATE(AVG(access_logs.participants_number),0) AS A , SUM(access_logs.participants_number) AS B FROM access_logs WHERE access_logs.conference_info_id = 10 AND prefecture LIKE '%奈良県%' OR access_logs.conference_info_id = 10 AND prefecture LIKE '%群馬県%' GROUP BY prefecture ; ### To Do 1.カラムを指定する(hostIP) 2.テーブルを指定する() 3.テスト29講演会データを指定する 4.ユニークの方法を調べる(GROUP BY) 5.ユーザーエージェントは「Firefox」からのアクセスを除外(access_logs.userAgent) 6.確認 https://hacknote.jp/archives/31314/ SELECT count(DISTINCT hostIP) FROM access_logs WHERE access_logs.conference_info_id = 29 AND access_logs.userAgent NOT LIKE '%Firefox%' AND entryPage LIKE '%live400%' ; ### To Do 1.カラムを指定する(hostIP) 2.テーブルを指定する() 3.滞在時間計算を調べる 4.記載 5.確認 https://www.wakuwakubank.com/posts/335-mysql-sql-function-date/#index_id26 SELECT accessLogId , accessTime , stopTime , DATE_FORMAT(TIMEDIFF(stopTime,accessTime),'%H:%i') AS stayTime FROM access_logs ; 3問目 GROUP BYで解く(サブクエリ) SELECT hostIP FROM access_logs WHERE access_logs.conference_info_id = 29 AND access_logs.userAgent NOT LIKE '%Firefox%' AND entryPage LIKE '%live400%' ; ### To Do 1.カラムを指定する() 2.テーブルを指定する(enquete_answers) 3.平均値の求め方を調べる 4.イベントごとの平均を求める 5.全イベントの平均値を求める 6.確認 SELECT conference_info_id , AVG(answer1) , (SELECT AVG(answer1) FROM enquete_answers) AS 'A1' , AVG(answer2) , (SELECT AVG(answer2) FROM enquete_answers) , AVG(answer3) , (SELECT AVG(answer3) FROM enquete_answers) , AVG(answer4) , (SELECT AVG(answer4) FROM enquete_answers) , AVG(answer5) , (SELECT AVG(answer5) FROM enquete_answers) FROM enquete_answers GROUP BY conference_info_id ; ### To Do 1.カラムを指定する() 2.テーブルを指定する(access_logs) 3.フォーマットの指定方法を調べる 4.判定方法を調べる 5.判定する 6.確認 SELECT accessLogId , DATE_FORMAT(accessTime,'%Y-%m-%d %k:%i') , IF(STR_TO_DATE('2023-01-27 19:10:00') > accessTime,"TRUE" , "FALSE") FROM access_logs WHERE access_logs.conference_info_id = 1 ; ### To Do 1.カラムを指定する() 2.テーブルを指定する(access_logs) 3.時間調べる(1番遅い人) 4.フォーマット変更 5.講演会ごとにまとめる 6.確認 キーワード:相関サブクエリー SELECT conference_info_id , accessLogId_MAX , DATE_FORMAT(MAX(accessTime),'%Y-%m-%d %k:%i') FROM access_logs WHERE accessLogId_MAX = ( SELECT MAX(accessTime) FROM access_logs AS AL2 WHERE AL2.conference_info_id = access_logs.conference_info_id ) GROUP BY conference_info_id ; ### To Do 1.INSERTの使い方を調べる 2.書く 3.確認 4. 5. 6. INSERT INTO sql_plactice_logs (created_by, conf_name, created_at, updated_at) VALUES ("チームC", "上妻講演会", NOW(), NOW()) ; ### To Do 1.UPDATEの使い方を調べる 2.書く 3.確認 4. 5. 6. UPDATE sql_plactice_logs SET conf_info = '角田さん遅いなー' , updated_at = NOW() WHERE created_by = "チームC" ; ### To Do 1.1の問題をコピーしてくる 2.問題文に沿ってカラムを書く 3.Valueを指定する 4.確認 5. 6. INSERT INTO sql_plactice_logs (created_by, conf_name, conf_date, conf_time, access_time, stop_time, participants_number, created_at, updated_at) VALUES ("チームC1", "sumida講演会", CURDATE(),ADDTIME(NOW(), '01:00:00'), NOW(), ADDTIME(NOW(), '01:00:00'), 6, NOW(), NOW()) , ("チームC2", "すみだ講演会", DATE_ADD(CURDATE() ,INTERVAL 1 DAY), DATE_ADD(NOW() ,INTERVAL 1 DAY), NOW(), ADDTIME(NOW(), '01:00:00'), 6, NOW(), NOW()) , ("チームC3", "角田講演会", DATE_ADD(CURDATE() ,INTERVAL 1 MONTH), DATE_ADD(NOW() ,INTERVAL 1 MONTH), NOW(), ADDTIME(NOW(), '01:00:00'), 6, NOW(), NOW()) ; ADDTIME(CURTIME(), '01:00:00'); ### To Do 1.問題2の答えをコピーしてくる 2.本日講演の出し方を調べる 3.滞在時間を算出する 4.確認 5. 6. UPDATE sql_plactice_logs SET lecture_today = CASE WHEN DATE(NOW()) = conf_date THEN 1 ELSE 0 END , updated_at = NOW() WHERE created_by = "チームC" ; lecture_today ### To Do 1.カラムを指定する 2.テーブル指定する 3.WHERE(かつ)を指定 4.確認 5. 6. SELECT * FROM enquete_answers WHERE conference_info_id = 3 AND answer1 = 2 AND answer2 = 3 AND answer3 = 3 AND answer4 = 3 AND answer5 = 1 ; ### To Do 1.カラムを指定する 2.テーブルを指定する 3.カラムを連結する 4.stoptimeを降順に並べ替え、10件だけ表示 5.日付のフォーマットを指定する 6.確認 SELECT CONCAT(IFNULL(prefecture,""),' - ',IFNULL( facility,""),' / ',IFNULL(name,"")) AS profile , DATE_FORMAT(accessTime,'%Y-%m-%d %k:%i:%s') AS accessTime , DATE_FORMAT(stopTime,'%Y-%m-%d %k:%i:%s') AS stopTime FROM access_logs ORDER BY stopTime DESC LIMIT 10 ; ### To Do 1. カラムを指定する 2. テーブルを指定する(access_logs) 3. 都道府県ごとに表示 4. 500人以上のみ表示 5. nullのレコードの非表示 6. 確認 SELECT prefecture , SUM(participants_number) AS participants_number FROM access_logs WHERE prefecture NOT IN ('NULL') GROUP BY prefecture HAVING participants_number >= 500 ; ### To Do 1. カラムを指定する 2. テーブルを指定する(access_logs) 3. 日付を絞る 4. IPで絞る 5. ファイアフォックスで絞る 6. 確認 SELECT user_lists.userID , user_lists.userPassword FROM user_lists INNER JOIN access_logs ON user_lists.userListId = access_logs.user_list_id WHERE access_logs.accessTime BETWEEN '2023-01-27 19:15:00' AND '2023-01-27 19:30:00' AND access_logs.hostIP = "142.53.10.72" AND access_logs.userAgent LIKE "%Firefox%" ; ### To Do 1. カラムを指定する 2. テーブルを指定する(access_logs) 3. アンケートログとユーザーIDリストを外部結合 4. ログインIDで絞る 5. アンケート1の解答が2 6. 終わりかな SELECT access_logs.prefecture , access_logs.facility , access_logs.name , enquete_answers.answer1 , user_lists.userID FROM access_logs LEFT JOIN access_logs ON user_lists.userListId = access_logs.user_list_id LEFT JOIN enquete_answers ON access_logs.accessLogId = enquete_answers.access_log_id WHERE userID = "RKCNo" AND answer1 = "2" ; ### To Do 1. カラムを指定する 2. テーブルを指定する(access_logs) 3. テーブルを結合 4. 福岡県に絞る 5. アンケートのnullを除外 6. テスト44講演会に絞る 7. 確認 SELECT access_logs.accessLogId , access_logs.prefecture , access_logs.facility , access_logs.name , enquete_answers.answer1 , enquete_answers.answer2 , enquete_answers.answer3 FROM access_logs INNER JOIN enquete_answers ON access_logs.accessLogId = enquete_answers.access_log_id WHERE access_logs.prefecture = '福岡県' AND access_logs.conference_info_id = 44 ; --- todo 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 ConferenceInfo.where(title: "タイトル") ConferenceInfo.where(conferenceInfoId: [25]) todo 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 #例 Discographyテーブルの1番最初のレコードを取得 ConferenceInfo.first ToDoリスト 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 ConferenceInfo.last #blogsテーブルのidが一番大きいレコードを取得 ToDoリスト 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 ConferenceInfo.find_by(confName:"テスト21講演会") confName テスト21講演会 ToDoリスト 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 AccessLog.limit(10) ToDoリスト 1.ActiveRecordでデータを指定する方法を調べる 2.試す 3.確認 #5つ目から3つのレコードを取得 AccessLog.offset(1900) ToDoリスト 1.ActiveRecordでカラムを指定する方法を調べる 2.試す 3.確認 #例 Discographyテーブルのnameカラムとartistカラムのデータを取得 @discography = Discography.select('name', 'artist') @discography = Discography.select(:name, :artist) #例 artistカラムの値が'ももいろクローバーZ'かつreleased_dateが'2011-07-27' のレコードを取得 @discography = Discography.where(artist: 'ももいろクローバーZ', released_date: '2011-07-27') AccessLog.select('accessLogId', 'prefecture', 'facility', 'name') ToDoリスト 1.ActiveRecordでデータの数を表示する方法を調べる 2.試す 3.確認 AccessLog.count ToDoリスト 1.ActiveRecordでデータの平均を表示する方法を調べる 2.試す 3.確認 AccessLog.average(:participants_number) participants_number ToDoリスト 1.ActiveRecordでデータの最高人数を表示する方法を調べる 2.試す 3.確認 AccessLog.maximum(:participants_number) .maximum ToDoリスト 1.ActiveRecordでデータの最低人数を表示する方法を調べる 2.試す 3.確認 AccessLog.minimum(:participants_number) .minimum(カラム名) ToDoリスト 1.ActiveRecordでデータの人数の合計を表示する方法を調べる 2.試す 3.確認 AccessLog.sum(:participants_number) ToDoリスト 1.ActiveRecordでアクセスログテーブルの入室時間が早い順を表示する方法を調べる 2.試す 3.確認 AccessLog.order(:accessTime) User.all.order(id: "DESC") ToDoリスト 1.ActiveRecordでアクセスログテーブルの入室時間が早い順を表示する方法を調べる 2.試す 3.確認 AccessLog.order(accessTime: "DESC") ToDoリスト 1.ActiveRecordでアクセスログテーブルの入室時間が遅い順を表示する方法を調べる 2.試す 3.確認 ToDoリスト 1.ActiveRecordでアクセスログテーブルのデータをランダムに1件のみ表示する方法を調べる 2.試す 3.確認 AccessLog AccessLog.all.sample AccessLog.where( 'accessLogId >= ?', rand(AccessLog.count) + 1 ).first AccessLog.offset( rand(AccessLog.count) ).first AccessLog.all.sample AccessLog.order("RAND()").first --- # Activerecord 2回目 ## READ文③ ToDoリスト 1.アクセスログテーブルの都道府県が佐賀県のデータを表示する方法を調べる 2.試す 3.確認 AccessLog.where(prefecture:"佐賀県") モデル名.where(カラム名: '値') ToDoリスト 1.アクセスログテーブルの都道府県が福岡県かつ柳沢病院のデータを表示する方法を調べる 2.試す 3.確認 AccessLog.where(prefecture: "福岡県", facility: "柳沢病院") User.where(name: "太郎", age: 25) # nameカラムが「太郎」かつageカラムが「25」のレコード全てを取得できる。 ToDoリスト 1.アクセスログテーブルの施設名が松野病院または千田病院のデータを表示する方法を調べる 2.試す 3.確認 AccessLog.where(facility: "松野病院").or(AccessLog.where(facility: "千田病院")) # nameカラムが「太郎」またはageカラムが「25」のレコード全てを取得できる。 User.where(name: "太郎").or(User.where(age: 25)) # nameカラムが「太郎」またはageカラムが「25」のレコード全てを取得できる。 - IN句を用いた書き方 User.where(id: [1, 5, 7]) AccessLog.where(facility: ["松野病院", "千田病院"]) ToDoリスト 1.アクセスログテーブルのユニークIDが空でないデータの数を表示する方法を調べる 2.試す 3.確認 AccessLog.count{ |uid| !uid.null? } AccessLog.count(uid=nil) モデル名.select("カラム名") p array.count{ |num| !num.nil? } モデルのコレクション.count(カラム名=nil) AccessLog.where.not(uid: nil).count AccessLog.where.not(uid: nil) ToDoリスト 1. アクセスログテーブルのユーザーリストIDが18~20を表示する方法を調べる 2. 昇順にする 3. 試す 4. 確認 User.where(id: [1, 5, 7]) User.where(age: 20..29) AccessLog.where(user_list_id: 18..20).order(:user_list_id) User.all.order(id:) ToDoリスト 1. アクセスログテーブルのユーザーエージェントにfirefoxという文字が含まれるデータを表示する方法を調べる 2. 試す 3. 確認 AccessLog.where("userAgent LIKE ?", "%firefox%") ToDoリスト 1. アクセスログテーブルの集合視聴人数が25人以上のデータを表示する方法を調べる 2. 試す 3. 確認 AccessLog.where(participants_number: 25..Float::INFINITY) AccessLog.where(participants_number: 25..) ToDoリスト 1. アクセスログテーブルのIPアドレスが「2.181.230.81」を表示する方法を調べる 2. カラムの指定(都道府県、施設、氏名、IPアドレス) 3. 試す 4. 確認 AccessLog.where(participants_number: "2.181.230.81") AccessLog.where(hostIP: '2.181.230.81') .select(:prefecture, :facility, :name, :hostIP) AccessLog.where(ip_address: '2.181.230.81') .select(:id, :prefecture, :facility, :name, :ip_address) User.where(gender: "male").pluck(:name) ToDoリスト 1. アクセスログテーブルの都道府県ごとの集合視聴人数(participants_number)を集計する方法を調べる 2. 都道府県ごとの参加人数が500人以上のレコードのみを表示する方法を調べる 3. 都道府県がnullのレコードは表示なし方法を調べる 4. 表示はカラム名に都道府県名、値に集合視聴人数の合計を表示する方法を調べる 5. 試す 6. 確認 AccessLog.where.not(prefecture: nil) .group(:prefecture) .having("SUM(participants_number) >= ?", 500) .pluck("prefecture, SUM(participants_number)") AccessLog.where.not(prefecture: nil) .group(:prefecture) .having("SUM(participants_number) >= ?", 500) .select(:prefecture, SUM(:participants_number)) ToDoリスト 1. 講演会名「テスト29講演会」のアクセスログを取得 2. 本番視聴のログのみを表示する方法を調べる 3. ユーザーエージェントに「Firefox」と含まれているのアクセスを除外 4. 表示はカラム名にIPアドレスのユニークな人数を表示する方法を調べる 5. 試す 6. 確認 ```ruby AccessLog.where(conference_info_id: 29) .where("entryPage LIKE ? ", "%live%") .where.not("userAgent LIKE ? ", "%Firefox%") .select(:hostIP).distinct.count ``` userAgent モデル名.select(:取得列).distinct ```ruby AccessLog.where(conference_info_id: 29) .where("entryPage LIKE ? AND userAgent NOT LIKE ?", "%live%", "%Firefox%") .select(:hostIP).distinct.count ``` ToDoリスト 1. アクセスログID「46」に紐づいているアンケートログテーブルのデータを表示 2. アンケートログテーブルのカラムをすべて表示 3. 試す 4. 確認 EnqueteAnswer.where(access_log_id: 46) 正解例 AccessLog.find(46).enquete_answer ToDoリスト 1. カンファレンスインフォテーブルのカンファレンスインフォID「39」のカンファレンスインフォID、講演会名、講演会日時を表示 2. カンファレンスインフォID「39」に紐づいているアクセスログテーブルから都道府県、施設、氏名を表示 3. 試す 4. 確認 User.where(family_id:1).pluck(:name) ConferenceInfo.where(conferenceInfoId: 39).select(:conferenceInfoId,:confName,:conferenceDate) x ConferenceInfo.find(39).access_log.select(:prefecture,:facility,:name) access_log Actress.joins(:movies).select("actresses.*, movies.*").first.title ConferenceInfo.joins(:access_log).select("conference_infos.conferenceInfoId,conference_infos.confName,conference_infos.conferenceDate,access_logs.prefecture,access_logs.facility,access_logs.name").where(conferenceInfoId: 39) 正解例 ConferenceInfo.left_outer_joins(:access_log) .where(conferenceInfoId: 39) .select( :conferenceInfoId, :confName, :conferenceDate, :prefecture, :facility, :name ) ToDoリスト 1. アクセスログテーブルのカンファレンスインフォIDが「3」のデータに紐づけられているアンケートログテーブルのデータを取得 2. カラムはアクセスログテーブルのアクセスログID、都道府県、氏名、アンケートログテーブルの問1の答え、問2の答えを取得 3. アンケートログテーブルにデータが無い場合はそのレコードを表示しない 4. 試す 5. 確認 AccessLog.joins(:enquete_answer) .where(conference_info_id: 3) .select( :accessLogId, :prefecture, :name, :answer1, :answer2 ) ToDoリスト 1. カンファレンスインフォテーブルの講演会名「テスト14講演会」のデータを出力 2. カンファレンスインフォテーブルに紐づいているユーザーIDリストテーブルのデータも出力 3. カンファレンスインフォテーブルのカラムは全て表示、ユーザーIDリストテーブルのカラムはログインIDとパスワードのみ表示 4. SQLのクエリ回数を減らすために今回の取得したテーブルはキャッシュしておく 5. 試す 6. 確認 ConferenceInfo.joins(:user_list) .where(confName: "テスト14講演会") .select( "conference_infos.*", :userID, :userPassword ) ConferenceInfo.preload(:user_list) .where(confName: "テスト14講演会") .select( "conference_infos.*", :userID, :userPassword ) eager_load --- ### h3 230419 READ文⑤ ToDoリスト 1. カンファレンスインフォテーブルのカンファレンスインフォID「47」のカンファレンスインフォID、講演会名、講演会日時を表示 2. カンファレンスインフォID「47」に紐づいているアクセスログテーブルから都道府県、施設、氏名を表示 3. カンファレンスインフォID「47」に紐づいているユーザーIDリストからログインIDとパスワードを表示 4. 試す 5. 確認 ConferenceInfo.where(conferenceInfoId: 47) .joins(:access_log, :user_list) .select( :conferenceInfoId, :confName, :conferenceDate, :prefecture, :facility, :name, :userID, :userPassword ) # ルール①を適用 A.joins([:b, :g]) # ルール②を適用 A.joins(:b, :g) ToDoリスト 1. カンファレンスインフォテーブルのカンファレンスインフォID「21」のカンファレンスインフォID、講演会名、講演会日時を表示 2. カンファレンスインフォID「21」に紐づいているアクセスログテーブルから都道府県、施設、氏名を表示 3. アクセスログテーブルのに紐づいているアンケートログテーブルから問1の答えと問2の答えを表示 4. 試す 5. 確認 ConferenceInfo.where(conferenceInfoId: 21) .joins(access_log: :enquete_answer) .select( :conferenceInfoId, :confName, :conferenceDate, :prefecture, :facility, :name, :answer1, :answer2 ) Article.joins(comments: :guest) ToDoリスト 1. アクセスログの2023年2月6日の14:00~14:15の間にアクセスされた、IP(202.237.113.26)でChromeを使って視聴している方のログインIDとパスワードを表示 2. カラムはアクセスログIDとログインIDとパスワードを表示 3. 試す 4. 確認 AccessLog.joins(:user_list) .where(hostIP: "202.237.113.26") .where("userAgent LIKE ?", "%Chrome%") .where("accessTime BETWEEN ? AND ?", '2023-02-06 14:00:00', '2023-02-06 14:15:00') .select( :accessLogId, :userID, :userPassword ) .where("列名 LIKE ?", "%値%") # 値(文字列)を含む Pattern.where(“accessTime BETWEEN ? AND ?”, '2023-02-06 14:00:00', '2023-02-06 14:15:00') SQL access_logs.accessTime BETWEEN '2023-02-06 14:00:00' AND '2023-01-27 19:30:00' ToDoリスト 1. 講演会ごとの視聴者を求める(groupby) 2. sumで視聴者数の合計を求める 3. orderbyで並び替え 4. カラム指定 5. 試す 6. 確認 上位10位までに制限する例 TestModel.limit(10).order('sum_score desc').group(:user_id).sum(:score) AccessLog.all.order(participants_number: 'desc') .group(:conference_info_id) .sum(:participants_number) AccessLog.select('sum(participants_number) as tot') .order('tot desc') .group(:conference_info_id) <!-- .sum(:participants_number) --> AccessLog AccessLog conference_info_id participants_number Job.group(:user_id).select('SUM(total_days) as tot').order('tot desc') --- ConferenceInfo.joins(:access_log) .group(:conferenceInfoId) .select('sum(participants_number) as tot', 'conferenceInfoId') .order('tot DESC') --- ToDoリスト 1. 講演会の視聴者数ランキング1位(多い方)のアクセスログを全て表示 2. 試す 3. 確認 AccessLog.select('select('sum(participants_number) as tot') .order('tot desc') .group(:conference_info_id) .limit(1) as first') .where(conference_info_id = first) conference_info_id AccessLog.select('sum(participants_number) as tot').order('tot desc') .group(:conference_info_id) .limit(1) AccessLog.select('sum(participants_number) as tot').order('tot desc') .group(:conference_info_id) .limit(1) ConferenceInfo.joins(:access_log) .group(:conferenceInfoId) .order('SUM(participants_number) DESC') .first.access_log --- ToDoリスト 1. 入室時間が「2023-02-08」でライブ配信のアクセスログを表示 2. 参加登録の都道府県がnullの物は表示しない 3. 参加登録の都道府県ごとに見たとき、アンケートログの問1の答えが「1」と回答された数が「2」以上の都道府県を表示 4. カラムはアクセスログテーブルの「アクセスログID(nullでok)」「都道府県」とアンケートログテーブルの 「都道府県ごとの問1の答えの数」を表示 5. 試す 6. 確認 AccessLog.joins(:enquete_answer) .where('accessTime LIKE ?','%2023-02-08%') .where('entryPage LIKE ?','%live%') .where.not(prefecture: nil) .group(:prefecture) .having('count(answer1 = 1) >= 2') .select(:accessLogid, :prefecture, "count(answer1 = 1)") .where.not(prefecture: nil) ToDoリスト 1. データを作成するメソッドを調べる 2. 試す 3. 確認 SqlPlacticeLog.create(conf_name:'上妻講演会',created_by:'チームC') ToDoリスト 1. データの更新方法を調べる 2. 試す 3. 確認 SqlPlacticeLog #モデル名.update(カラム名: データ)で保存されます。 #update前にfindでupdateをするデータを取得します。 #以下が例です。 post= Post.find(1) post.update(name: "記事2", title: "higehige") SqlPlacticeLog.find(84).update(conf_info: "スミダマーン") ToDoリスト 1. 問1をコピーしてくる 2. データ作成者にチーム名を入力1件目、2件目同様 3. 講演会日に1件目は本日の日付、2件目は明日の日付 4. 講演会時間に1件目は現在時刻、2件目は現在時刻を明日の日付にしたもの 5. その他のカラムはNullとする 6. 試す 7. 確認 SqlPlacticeLog.create(conf_name:'上妻講演会',created_by:'チームC') users テーブルに 2つ のレコードを保存する例を考えてみます。 User.create( [ { name: 'taro', age: 20 }, { name: 'hanako', age: 25 } ] ) SqlPlacticeLog.create( [ { created_by: 'チームC', conf_date: Time.zone.today, conf_time: Time.now }, { created_by: 'チームC', conf_date: Time.zone.tomorrow, conf_time: Time.now + 24 * 60 * 60 } ] ) >> Time.zone.today => Sat, 25 Feb 2017 >> Time.zone.yesterday => Fri, 24 Feb 2017 >> Time.zone.tomorrow => Sun, 26 Feb 2017 Ruby >> time = Time.now => 2017-02-25 12:18:31 +0900 1 2 >> time = Time.now => 2017-02-25 12:18:31 +0900 Ruby >> Time.now + 24 * 60 * 60 => 2017-02-26 13:18:59 +0900 >> Time.now - 24 * 60 * 60 => 2017-02-24 13:19:10 +0900 1 2 3 4 >> Time.now + 24 * 60 * 60 => 2017-02-26 13:18:59 +0900 >> Time.now - 24 * 60 * 60 => 2017-02-24 13:19:10 +0900 ToDoリスト 1. 本日のものを条件指定する 2. lecture_todayをtrueに更新する 3. 試す 4. 確認 SqlPlacticeLog.where(conf_date:Time.zone.today, created_by: 'チームC').update(lecture_today: true) AccessLog.where(prefecture: "福岡県", facility: "柳沢病院") ToDoリスト 1. 自分のチームが作成したレコードを絞る 2. 削除する 3. 試す 4. 確認 SqlPlacticeLog.where(created_by: 'チームC').update(lecture_today: true) SqlPlacticeLog.where(created_by: 'チームC').destroy_all --- <%% sumida = ConferenceInfo.left_outer_joins(:access_log).where.not(access_logs:{name: nil}).group(:confName) .select( :confName, :conferenceDate, :name ) %> <% each do |senya|%> <div> <%= senya.confName %> <%= senya.conferenceDate %> <%= senya.name %> </div> div{ display:flex; } <% end %> ConferenceInfo.left_outer_joins(:access_log).where.not(access_logs:{name: nil}).group(:confName) .select( :confName, :conferenceDate, :name ) where.not(uid: nil) .group(:confName) [{"conferenceInfoId":null,"confName":"テスト10講演会","conferenceDate":"2023-02-03","name":"佐伯 南里"},{"conferenceInfoId":null,"confName":"テスト11講演会","conferenceDate":"2023-01-24","name":"津田 幸樹"},

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully