Search Results

Search found 6276 results on 252 pages for 'join'.

Page 15/252 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • MySQL 5 multiple JOIN syntax not working in MySQL 4

    - by draco
    Hello all, the current SQL query works fine locally on MAMP 1.8.4 running MySQL 5.1.37. SELECT EL.log_actions, EL.log_date, EL.log_value, EL.log_type, EA.admins_name, EU.users_name, EU.users_matric FROM events_log EL JOIN events_users EU USING (users_id) JOIN events_admins EA USING (admins_id) ORDER BY EL.log_id DESC LIMIT 0, 10 However, when I bring this query live to production server which is running MySQL 4.1.22-standard, the following error occurred (whether or not there are data in the entry). A Database Error Occurred Error Number: 1054 Unknown column 'sceclub_exclaim2007.EU.admins_id' in 'on clause' SELECT EL.log_actions, EL.log_date, EL.log_value, EL.log_type, EA.admins_name, EU.users_name, EU.users_matric FROM events_log EL JOIN events_users EU USING (users_id) JOIN events_admins EA USING (admins_id) ORDER BY EL.log_id DESC LIMIT 0, 20 This is based on CodeIgniter 1.7.2 and both production and development are running the same set of database. Database tables events_users: users_id users_name users_credits users_matric users_redeem events_admins: admins_id admins_email admins_name admins_pass admins_date admins_modified admins_last_login events_attendance: attendance_id users_id events_id events_events: events_id events_name events_venue events_time events_desc events_pass events_log:log_id admins_id log_actions log_date log_value users_id log_type I'm new to MySQL so I'm not aware of any difference in versions or what could be a possible cause, thank you in advance! Tried googling for MySQL4 difference to no avail too. Also tried using SELECT EL.log_actions, EL.log_date, EL.log_value, EL.log_type, EA.admins_name, EU.users_name, EU.users_matric FROM events_log EL JOIN events_users EU where EL.users_id = EU.users_id JOIN events_admins EA USING EL.admins_id = EA.admins_id ORDER BY EL.log_id DESC LIMIT 0, 10 But then I got the error in both production and development. A Database Error Occurred Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN events_admins EA USING EL.admins_id = EA.admins_id ORDER BY' at line 8 SELECT EL.log_actions, EL.log_date, EL.log_value, EL.log_type, EA.admins_name, EU.users_name, EU.users_matric FROM events_log EL JOIN events_users EU where EL.users_id = EU.users_id JOIN events_admins EA USING EL.admins_id = EA.admins_id ORDER BY EL.log_id DESC LIMIT 0, 20 If you can point me to some resources where I can read up more on MySQL 4 syntax to achieve the same thing effect like I did with MySQL 5 syntax, please let me know. Thanks again!

    Read the article

  • How to avoid Cartesian product in an INNER JOIN query?

    - by flhe
    I have 6 tables, let's call them a,b,c,d,e,f. Now I want to search all the colums (except the ID columns) of all tables for a certain word, let's say 'Joe'. What I did was, I made INNER JOINS over all the tables and then used LIKE to search the columns. INNER JOIN ... ON INNER JOIN ... ON.......etc. WHERE a.firstname ~* 'Joe' OR a.lastname ~* 'Joe' OR b.favorite_food ~* 'Joe' OR c.job ~* 'Joe'.......etc. The results are correct, I get all the colums I was looking for. But I also get some kind of cartesian product, I get 2 or more lines with almost the same results. How can i avoid this? I want so have each line only once, since the results should appear on a web search.

    Read the article

  • PostgreSQL JOIN with array type with array elements order, how to implement?

    - by Adiasz
    Hello I have two tables in database: CREATE TABLE items( id SERIAL PRIMARy KEY, ... some other fields ); This table contains come data row with unique ID. CREATE TABLE some_choosen_data_in_order( id SERIAL PRIMARy KEY, id_items INTEGER[], ); This table contains array type field. Each row contains values of IDs from table "items" in specyfic order. For example: {2,4,233,5}. Now, I want to get data from table "items" for choosen row from table "some_choosen_data_in_order" with order for elements in array type. The my attempt is JOIN: SELECT I.* FROM items AS I JOIN some_choosen_data_in_order AS S ON I.id = ANY(S.id_items) WHERE S.id = ? Second attempt was subquery like: SELECT I.* FROM items AS I WHERE I.id = ANY (ARRAY[SELECT S.id_items FROM some_choosen_data_in_order WHERE id = ?]) But none of them keep IDs order in array field. Could You help me, how to get data from "items" table with correspond with array IDs order from "some_choosen_data_in_order" table for specyfic row?

    Read the article

  • SQL: How to join a view with a table?

    - by gamerzfuse
    CREATE VIEW qtyorderedview AS SELECT titleditors.title_id, titleditors.ed_id, salesdetails.title_id, salesdetails.qty_shipped FROM titleditors, salesdetails WHERE titleditors.title_id = salesdetails.title_id I am using the above SQL statement to create a view. I need to show Editors First Name, Last Name, City where they shipped more than 50 books. The three tables I have are: create table editors ( ed_id char(11), ed_lname varchar(20), ed_fname varchar(20), ed_pos varchar(12), phone varchar(10), address varchar(30), city varchar(20), state char(2), zip char(5), ed_boss char(11)); create table titleditors ( ed_id char(11), title_id char(6), ed_ord integer); create table salesdetails ( sonum integer, qty_ordered integer, qty_shipped integer, title_id char(6), date_shipped date); Can anyone tell me what the second Join code would be to create this result? My first view works fine, but I don't know how to join it to the second table to achieve this result? I didn't make the tables, I just have to work with what I was given. Thanks in advance!

    Read the article

  • Is using Natural Join or Implicit column names not a good practice when writing SQL in a programming

    - by Jian Lin
    When we use Natural Join, we are joining the tables when both table have the same column names. But what if we write it in PHP and then the DBA add some more fields to both tables, then the Natural Join can break? The same goes for Insert, if we do a insert into gifts values (NULL, "chocolate", "choco.jpg", now()); then it will break the code as well as contaminating the table when the DBA adds some fields to the table (example as column 2 or 3). So it is always best to spell out the column names when the SQL statements are written inside a programming language and stored in a file in a big project.

    Read the article

  • How can I do a right outer join where both tables have a where clause?

    - by cdeszaq
    Here's the scenario: I have 2 tables: CREATE TABLE dbo.API_User ( id int NOT NULL, name nvarchar(255) NOT NULL, authorization_key varchar(255) NOT NULL, is_active bit NOT NULL ) ON [PRIMARY] CREATE TABLE dbo.Single_Sign_On_User ( id int NOT NULL IDENTITY (1, 1), API_User_id int NOT NULL, external_id varchar(255) NOT NULL, user_id int NULL ) ON [PRIMARY] What I am trying to return is the following: is_active for a given authorization_key The Single_Sign_On_User.id that matches the external_id/API_User_id pair if it exists or NULL if there is no such pair When I try this query: SELECT Single_Sign_On_User.id, API_User.is_active FROM API_User LEFT OUTER JOIN Single_Sign_On_User ON Single_Sign_On_User.API_User_id = API_User.id WHERE Single_Sign_On_User.external_id = 'test_ext_id' AND API_User.authorization_key = 'test' where the "test" API_User record exists but the "test_ext_id" record does not, and with no other values in either table, I get no records returned. When I use: SELECT Single_Sign_On_User.id, API_User.is_active FROM API_User LEFT OUTER JOIN Single_Sign_On_User ON Single_Sign_On_User.API_User_id = API_User.id WHERE API_User.authorization_key = 'test' I get the results I expect (NULL, 1), but that query doesn't allow me to find the "test_ext_id" record if it exists but would give me all records associated with the "test" API_User record. How can I get the results I am after?

    Read the article

  • What is difference between Where and Join in linq ?

    - by Freshblood
    hello What is difference between of these 2 queries ? they are completely equal ? from order in myDB.OrdersSet from person in myDB.PersonSet from product in myDB.ProductSet where order.Persons_Id==person.Id && order.Products_Id==product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name }; and from order in myDB.OrdersSet join person in myDB.PersonSet on order.Persons_Id equals person.Id join product in myDB.ProductSet on order.Products_Id equals product.Id select new { order.Id, person.Name, person.SurName, product.Model,UrunAdi=product.Name };

    Read the article

  • How should I join these 3 SQL queries in Oracle?

    - by Nazgulled
    I have these 3 queries: SELECT title, year, MovieGenres(m.mid) genres, MovieDirectors(m.mid) directors, MovieWriters(m.mid) writers, synopsis, poster_url FROM movies m WHERE m.mid = 1; SELECT AVG(rating) FROM movie_ratings WHERE mid = 1; SELECT COUNT(rating) FROM movie_ratings WHERE mid = 1; And I need to join them into a single query. I was able to do it like this: SELECT title, year, MovieGenres(m.mid) genres, MovieDirectors(m.mid) directors, MovieWriters(m.mid) writers, synopsis, poster_url, AVG(rating) average, COUNT(rating) count FROM movies m INNER JOIN movie_ratings mr ON m.mid = mr.mid WHERE m.mid = 1 GROUP BY title, year, MovieGenres(m.mid), MovieDirectors(m.mid), MovieWriters(m.mid), synopsis, poster_url; But I don't really like that "huge" GROUP BY, is there a simpler way to do it?

    Read the article

  • MySQL : select/join on strings as fieldnames - is this possible?

    - by Dylan
    I can retrieve all column names from table 'categories' with : SELECT col.column_name FROM information_schema.columns AS col WHERE col.table_schema= database() and col.table_name = "categories" This produces a resultset like this : column_name ----------------- categoryID name description I can retrieve all values for a specific category with : SELECT * FROM categories AS c WHERE c.categoryID=12345 this results in a resultset like this: categoryID | name | description ------------------------------------------------ 12345 | test | this is a test Now I would like to get some kind of join of above selects to get a resultset that looks something like this : fieldname | value ---------------------------------------- categoryID | 12345 name | test description | this is a test Does anyone know if this is possible ? Can you do a join on strings that come from another select ?? The reason for this is that I'm writing a universal stored procedure that outputs all fields + their values from a table, without knowing what fields there are in the table. (The tablename is given in a parameter)

    Read the article

  • What is wrong with my SQL syntax for an UPDATE with a JOIN?

    - by Phil H
    I have two tables, related by a common key. So TableA has key AID and value Name and TableB has keys AID, BID and values Name, Value: AID Name 74 Alpha AID BID Name Value 74 4 Beta Brilliance I would like to update the TableB Value here from Brilliance to Barmy, using just the Name fields. I thought I could do it via an UPDATE containing a JOIN, but Access (I know...) is complaining with 'Syntax error (missing operator) in query expression ' and then everything from 'Barmy' here: UPDATE tB SET tB.BValue='Barmy' FROM TableB tB INNER JOIN TableA tA ON tB.AID=tA.AID WHERE tB.Name='Beta' AND tA.Name='Alpha'; What is my heinous crime? Or is it just Access not conforming?

    Read the article

  • Want to avoid the particular rows from select join query... See description

    - by OM The Eternity
    I have a Select Left Join Query whis displays me the rows for the latest changedone(its a time) column name ("field" should not be equal) column name ("trackid" should not be equal), and column name "Operation should be "UPDATE" ", below is the query I am talking about... SELECT j1. * FROM jos_audittrail j1 LEFT OUTER JOIN jos_audittrail j2 ON ( j1.trackid != j2.trackid AND j1.field != j2.field AND j1.changedone < j2.changedone ) WHERE j1.operation = 'UPDATE' AND j2.id IS NULL Now here I don't want a row to be displayed with a two particular column's value i.e. "field's value" the value is "LastvisitDate" and "hits" Now if if append the condition in the above query that " AND j1.field != 'lastvistDate' AND j1.field != 'hits' " theni do not get any result... The table structure is jos_audittrail: id trackid operation oldvalue newvalue table_name live changedone(its a time) I hope i have given the details properly If u still find something missing I will try to provide it more better way... Pls help me to avoid those two rows with those to mentioned value of "field"

    Read the article

  • How can I do a left outer join where both tables have a where clause?

    - by cdeszaq
    Here's the scenario: I have 2 tables: CREATE TABLE dbo.API_User ( id int NOT NULL, name nvarchar(255) NOT NULL, authorization_key varchar(255) NOT NULL, is_active bit NOT NULL ) ON [PRIMARY] CREATE TABLE dbo.Single_Sign_On_User ( id int NOT NULL IDENTITY (1, 1), API_User_id int NOT NULL, external_id varchar(255) NOT NULL, user_id int NULL ) ON [PRIMARY] What I am trying to return is the following: is_active for a given authorization_key The Single_Sign_On_User.id that matches the external_id/API_User_id pair if it exists or NULL if there is no such pair When I try this query: SELECT Single_Sign_On_User.id, API_User.is_active FROM API_User LEFT OUTER JOIN Single_Sign_On_User ON Single_Sign_On_User.API_User_id = API_User.id WHERE Single_Sign_On_User.external_id = 'test_ext_id' AND API_User.authorization_key = 'test' where the "test" API_User record exists but the "test_ext_id" record does not, and with no other values in either table, I get no records returned. When I use: SELECT Single_Sign_On_User.id, API_User.is_active FROM API_User LEFT OUTER JOIN Single_Sign_On_User ON Single_Sign_On_User.API_User_id = API_User.id WHERE API_User.authorization_key = 'test' I get the results I expect (NULL, 1), but that query doesn't allow me to find the "test_ext_id" record if it exists but would give me all records associated with the "test" API_User record. How can I get the results I am after?

    Read the article

  • Multiple JOIN and SELECT Statements from eight tables

    - by user1486004
    I am trying to make an SQL statement that takes eight different numbers and searches eight different tables from one database for the corresponding value. I keep getting invalid syntax, but I can't figure out why. Here is my code: SELECT cable_length.ID, drawing.ID, optional.ID, output_type.ID, pressure_range.ID, pressure_type.ID, series.ID, termination.ID FROM ( SELECT value AS cable_length FROM A1 WHERE A1.id = %s JOIN SELECT value AS drawing FROM A2 WHERE A2.id = %s, JOIN SELECT value AS optional FROM A3 WHERE A3.id = %s, JOIN SELECT value AS output_type FROM A4 WHERE A4.id = %s, JOIN SELECT value AS pressure_range FROM A5 WHERE A5.id = %s, JOIN SELECT value AS pressure_type FROM A6 WHERE A6.id = %s, JOIN SELECT value AS series FROM A7 WHERE A7.id = %s, JOIN SELECT value AS termination FROM A8 WHERE A8.id = %s ); The %s will be changed to numbers only. The column name in each database is "ID" and "Value". I want to search by "ID" and return "Value". Any help is greatly appreciated.

    Read the article

  • Python os.path.join on Windows

    - by Jim
    I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the docs if I say: os.path.join('c:', 'sourcedir') I get "C:sourcedir". According to the docs, this is normal, right? But when I use the copytree command, Python will output it the desired way, for example: import shutil src = os.path.join('c:', 'src') dst = os.path.join('c':', 'dst') shutil.copytree(src, dst) Here is the error code I get: WindowsError: [Error 3] The system cannot find the path specified: 'C:src/*.*' If I wrap the os.path.join with os.path.normpath I get the same error. If this os.path.join can't be used this way, then I am confused as to its purpose. According to the pages suggested by Stack Overflow, slashes should not be used in join—that is correct, I assume?

    Read the article

  • SQL "JOIN" vs. "INNER JOIN"?

    - by froadie
    I recently came across a query that implements a join using just the "JOIN" keyword. On researching I saw that when using a join in SQL without specifying INNER or OUTER, the default is an INNER JOIN. I've never come across this syntax before; all the SQL I've written/read/worked with specifies INNER or some sort of OUTER (LEFT, RIGHT, FULL...). Is there any reason not to rely on the default? Is the plain JOIN widely used? What are the coding standards regarding JOIN vs. INNER JOIN?

    Read the article

  • double left MYSQL join?

    - by Haroldo
    I've been trying left joins but as there are 2 joins, i think the problem is the 2nd join roots from table_B not table_A. i am not getting any results where there is the required data in the db. I am not getting a query error the query (simplified) SELECT events.*, ven.*, events_genres.* FROM events LEFT JOIN ven //OPTIONAL JOIN ON events.ven_id = ven.ven_id //OPTIONAL JOIN LEFT JOIN events_genres //REQUIRED JOIN ON events.event_id = events_genres.event_id //REQUIRED JOIN WHERE events.date >= '$this->now' AND WHERE events_genres.g_id = $g_id //REQUIRED MATCH ORDER BY date ven = optional, i'll have the info if its there. events_genres = required, i dont want any results that do not have a genre

    Read the article

  • Python os.path.join

    - by Jim
    Hello, I am trying to learn python and am making a program that will output a script. I want to use os.path.join but am pretty confused (I know I am very bad at scripting/programming) See, according to the docs ( http://docs.python.org/library/os.path.html ) if I say os.path.join('c:', 'sourcedir') I get C:sourcedir as it's output. According to the docs, this is normal (right?) But when I use the copytree command, Python will output it the desired way, for example import shutil src = os.path.join('c:', 'src') dst = os.path.join('c':', 'dst') shutil.copytree(src, dst) Here is the error code I get WindowsError: [Error 3] The system cannot find the path specified: 'C:src/.' If I wrap the os.path.join with os.path.normpath I get the same error If this os.path.join can't be used this way, then I am confused as to its purpose According to the pages suggested by Stack Overflow, slashes should not be used in join--that is correct I assume? Thanks guys(girls) for your help

    Read the article

  • MySQL inner join different results

    - by Darryl at NetHosted
    I am trying to work out why the following two queries return different results: SELECT DISTINCT i.id, i.date FROM `tblinvoices` i INNER JOIN `tblinvoiceitems` it ON it.userid=i.userid INNER JOIN `tblcustomfieldsvalues` cf ON it.relid=cf.relid WHERE i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' and SELECT DISTINCT i.id, i.date FROM `tblinvoices` i WHERE i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' Obviously the difference is the inner join here, but I don't understand why the one with the inner join is returning less results than the one without it, I would have thought since I didn't do any cross table references they should return the same results. The final query I am working towards is SELECT DISTINCT i.id, i.date FROM `tblinvoices` i INNER JOIN `tblinvoiceitems` it ON it.userid=i.userid INNER JOIN `tblcustomfieldsvalues` cf ON it.relid=cf.relid WHERE cf.`fieldid` =5 AND cf.`value` REGEXP '[A-Za-z]' AND i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' But because of the different results that seem incorrect when I add the inner join (it removes some results that should be valid) it's not working at present, thanks.

    Read the article

  • Refactoring a Single Rails Model with large methods & long join queries trying to do everything

    - by Kelseydh
    I have a working Ruby on Rails Model that I suspect is inefficient, hard to maintain, and full of unnecessary SQL join queries. I want to optimize and refactor this Model (Quiz.rb) to comply with Rails best practices, but I'm not sure how I should do it. The Rails app is a game that has Missions with many Stages. Users complete Stages by answering Questions that have correct or incorrect Answers. When a User tries to complete a stage by answering questions, the User gets a Quiz entry with many Attempts. Each Attempt records an Answer submitted for that Question within the Stage. A user completes a stage or mission by getting every Attempt correct, and their progress is tracked by adding a new entry to the UserMission & UserStage join tables. All of these features work, but unfortunately the Quiz.rb Model has been twisted to handle almost all of it exclusively. The callbacks began at 'Quiz.rb', and because I wasn't sure how to leave the Quiz Model during a multi-model update, I resorted to using Rails Console to have the @quiz instance variable via self.some_method do all the heavy lifting to retrieve every data value for the game's business logic; resulting in large extended join queries that "dance" all around the Database schema. The Quiz.rb Model that Smells: class Quiz < ActiveRecord::Base belongs_to :user has_many :attempts, dependent: :destroy before_save :check_answer before_save :update_user_mission_and_stage accepts_nested_attributes_for :attempts, :reject_if => lambda { |a| a[:answer_id].blank? }, :allow_destroy => true #Checks every answer within each quiz, adding +1 for each correct answer #within a stage quiz, and -1 for each incorrect answer def check_answer stage_score = 0 self.attempts.each do |attempt| if attempt.answer.correct? == true stage_score += 1 elsif attempt.answer.correct == false stage_score - 1 end end stage_score end def winner return true end def update_user_mission_and_stage ####### #Step 1: Checks if UserMission exists, finds or creates one. #if no UserMission for the current mission exists, creates a new UserMission if self.user_has_mission? == false @user_mission = UserMission.new(user_id: self.user.id, mission_id: self.current_stage.mission_id, available: true) @user_mission.save else @user_mission = self.find_user_mission end ####### #Step 2: Checks if current UserStage exists, stops if true to prevent duplicate entry if self.user_has_stage? @user_mission.save return true else ####### ##Step 3: if step 2 returns false: ##Initiates UserStage creation instructions #checks for winner (winner actions need to be defined) if they complete last stage of last mission for a given orientation if self.passed? && self.is_last_stage? && self.is_last_mission? create_user_stage_and_update_user_mission self.winner #NOTE: The rest are the same, but specify conditions that are available to add badges or other actions upon those conditions occurring: ##if user completes first stage of a mission elsif self.passed? && self.is_first_stage? && self.is_first_mission? create_user_stage_and_update_user_mission #creates user badge for finishing first stage of first mission self.user.add_badge(5) self.user.activity_logs.create(description: "granted first-stage badge", type_event: "badge", value: "first-stage") #If user completes last stage of a given mission, creates a new UserMission elsif self.passed? && self.is_last_stage? && self.is_first_mission? create_user_stage_and_update_user_mission #creates user badge for finishing first mission self.user.add_badge(6) self.user.activity_logs.create(description: "granted first-mission badge", type_event: "badge", value: "first-mission") elsif self.passed? create_user_stage_and_update_user_mission else self.passed? == false return true end end end #Creates a new UserStage record in the database for a successful Quiz question passing def create_user_stage_and_update_user_mission @nu_stage = @user_mission.user_stages.new(user_id: self.user.id, stage_id: self.current_stage.id) @nu_stage.save @user_mission.save self.user.add_points(50) end #Boolean that defines passing a stage as answering every question in that stage correct def passed? self.check_answer >= self.number_of_questions end #Returns the number of questions asked for that stage's quiz def number_of_questions self.attempts.first.answer.question.stage.questions.count end #Returns the current_stage for the Quiz, routing through 1st attempt in that Quiz def current_stage self.attempts.first.answer.question.stage end #Gives back the position of the stage relative to its mission. def stage_position self.attempts.first.answer.question.stage.position end #will find the user_mission for the current user and stage if it exists def find_user_mission self.user.user_missions.find_by_mission_id(self.current_stage.mission_id) end #Returns true if quiz was for the last stage within that mission #helpful for triggering actions related to a user completing a mission def is_last_stage? self.stage_position == self.current_stage.mission.stages.last.position end #Returns true if quiz was for the first stage within that mission #helpful for triggering actions related to a user completing a mission def is_first_stage? self.stage_position == self.current_stage.mission.stages_ordered.first.position end #Returns true if current user has a UserMission for the current stage def user_has_mission? self.user.missions.ids.include?(self.current_stage.mission.id) end #Returns true if current user has a UserStage for the current stage def user_has_stage? self.user.stages.include?(self.current_stage) end #Returns true if current user is on the last mission based on position within a given orientation def is_first_mission? self.user.missions.first.orientation.missions.by_position.first.position == self.current_stage.mission.position end #Returns true if current user is on the first stage & mission of a given orientation def is_last_mission? self.user.missions.first.orientation.missions.by_position.last.position == self.current_stage.mission.position end end My Question Currently my Rails server takes roughly 500ms to 1 sec to process single @quiz.save action. I am confident that the slowness here is due to sloppy code, not bad Database ERD design. What does a better solution look like? And specifically: Should I use join queries to retrieve values like I did here, or is it better to instantiate new objects within the model instead? Or am I missing a better solution? How should update_user_mission_and_stage be refactored to follow best practices? Relevant Code for Reference: quizzes_controller.rb w/ Controller Route Initiating Callback: class QuizzesController < ApplicationController before_action :find_stage_and_mission before_action :find_orientation before_action :find_question def show end def create @user = current_user @quiz = current_user.quizzes.new(quiz_params) if @quiz.save if @quiz.passed? if @mission.next_mission.nil? && @stage.next_stage.nil? redirect_to root_path, notice: "Congratulations, you have finished the last mission!" elsif @stage.next_stage.nil? redirect_to [@mission.next_mission, @mission.first_stage], notice: "Correct! Time for Mission #{@mission.next_mission.position}", info: "Starting next mission" else redirect_to [@mission, @stage.next_stage], notice: "Answer Correct! You passed the stage!" end else redirect_to [@mission, @stage], alert: "You didn't get every question right, please try again." end else redirect_to [@mission, @stage], alert: "Sorry. We were unable to save your answer. Please contact the admministrator." end @questions = @stage.questions.all end private def find_stage_and_mission @stage = Stage.find(params[:stage_id]) @mission = @stage.mission end def find_question @question = @stage.questions.find_by_id params[:id] end def quiz_params params.require(:quiz).permit(:user_id, :attempt_id, {attempts_attributes: [:id, :quiz_id, :answer_id]}) end def find_orientation @orientation = @mission.orientation @missions = @orientation.missions.by_position end end Overview of Relevant ERD Database Relationships: Mission - Stage - Question - Answer - Attempt <- Quiz <- User Mission - UserMission <- User Stage - UserStage <- User Other Models: Mission.rb class Mission < ActiveRecord::Base belongs_to :orientation has_many :stages has_many :user_missions, dependent: :destroy has_many :users, through: :user_missions #SCOPES scope :by_position, -> {order(position: :asc)} def stages_ordered stages.order(:position) end def next_mission self.orientation.missions.find_by_position(self.position.next) end def first_stage next_mission.stages_ordered.first end end Stage.rb: class Stage < ActiveRecord::Base belongs_to :mission has_many :questions, dependent: :destroy has_many :user_stages, dependent: :destroy has_many :users, through: :user_stages accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true def next_stage self.mission.stages.find_by_position(self.position.next) end end Question.rb class Question < ActiveRecord::Base belongs_to :stage has_many :answers, dependent: :destroy accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true end Answer.rb: class Answer < ActiveRecord::Base belongs_to :question has_many :attempts, dependent: :destroy end Attempt.rb: class Attempt < ActiveRecord::Base belongs_to :answer belongs_to :quiz end User.rb: class User < ActiveRecord::Base belongs_to :school has_many :activity_logs has_many :user_missions, dependent: :destroy has_many :missions, through: :user_missions has_many :user_stages, dependent: :destroy has_many :stages, through: :user_stages has_many :orientations, through: :school has_many :quizzes, dependent: :destroy has_many :attempts, through: :quizzes def latest_stage_position self.user_missions.last.user_stages.last.stage.position end end UserMission.rb class UserMission < ActiveRecord::Base belongs_to :user belongs_to :mission has_many :user_stages, dependent: :destroy end UserStage.rb class UserStage < ActiveRecord::Base belongs_to :user belongs_to :stage belongs_to :user_mission end

    Read the article

  • sybase - values from one table that aren't on another, on opposite ends of a 3-table join

    - by Lazy Bob
    Hypothetical situation: I work for a custom sign-making company, and some of our clients have submitted more sign designs than they're currently using. I want to know what signs have never been used. 3 tables involved: table A - signs for a company sign_pk(unique) | company_pk | sign_description 1 --------------------1 ---------------- small 2 --------------------1 ---------------- large 3 --------------------2 ---------------- medium 4 --------------------2 ---------------- jumbo 5 --------------------3 ---------------- banner table B - company locations company_pk | company_location(unique) 1 ------|------ 987 1 ------|------ 876 2 ------|------ 456 2 ------|------ 123 table C - signs at locations (it's a bit of a stretch, but each row can have 2 signs, and it's a one to many relationship from company location to signs at locations) company_location | front_sign | back_sign 987 ------------ 1 ------------ 2 987 ------------ 2 ------------ 1 876 ------------ 2 ------------ 1 456 ------------ 3 ------------ 4 123 ------------ 4 ------------ 3 So, a.company_pk = b.company_pk and b.company_location = c.company_location. What I want to try and find is how to query and get back that sign_pk 5 isn't at any location. Querying each sign_pk against all of the front_sign and back_sign values is a little impractical, since all the tables have millions of rows. Table a is indexed on sign_pk and company_pk, table b on both fields, and table c only on company locations. The way I'm trying to write it is along the lines of "each sign belongs to a company, so find the signs that are not the front or back sign at any of the locations that belong to the company tied to that sign." My original plan was: Select a.sign_pk from a, b, c where a.company_pk = b.company_pk and b.company_location = c.company_location and a.sign_pk *= c.front_sign group by a.sign_pk having count(c.front_sign) = 0 just to do the front sign, and then repeat for the back, but that won't run because c is an inner member of an outer join, and also in an inner join. This whole thing is fairly convoluted, but if anyone can make sense of it, I'll be your best friend.

    Read the article

  • join condition depends on the parameter

    - by sunglim
    Hi. I'm a sql newbie, I use mssql2005 I like to do join Action depnding on input parameter. CREATE PROCEDURE SelectPeriodicLargeCategoryData @CATEGORY_LEVEL CHAR(1), @CATEGORY_CODE VARCHAR(9) AS ... JOIN CATEGORY_AD_SYS CAS WITH(NOLOCK) ON CA.CATEGORY_ID = [[[[[ HERE ]]]] above the sql. if @CATEGORY_LEVEL = 'L' then I like to join on CAS.LCATEGORY else if @CATEGORY_LEVEL = 'M' then I like to join on CAS.MCATEGORY else if @CATEGORY_LEVEL = 'S' then I like to join on CAS.SCATEGORY ... how can I do this?

    Read the article

  • Help With LINQ: Mixed Joins and Specifying Default Values

    - by Corey O.
    I am trying to figure out how to do a mixed-join in LINQ with specific access to 2 LINQ objects. Here is an example of how the actual TSQL query might look: SELECT * FROM [User] AS [a] INNER JOIN [GroupUser] AS [b] ON [a].[UserID] = [b].[UserID] INNER JOIN [Group] AS [c] ON [b].[GroupID] = [c].[GroupID] LEFT JOIN [GroupEntries] AS [d] ON [a].[GroupID] = [d].[GroupID] WHERE [a].[UserID] = @UserID At the end, basically what I would like is an enumerable object full of GroupEntry objects. What am interested is the last two tables/objects in this query. I will be displaying Groups as a group header, and all of the Entries underneath their group heading. If there are no entries for a group, I still want to see that group as a header without any entries. Here's what I have so far: So from that I'd like to make a function: public void DisplayEntriesByUser(int user_id) { MyDataContext db = new MyDataContext(); IEnumberable<GroupEntries> entries = ( from user in db.Users where user.UserID == user_id join group_user in db.GroupUsers on user.UserID = group_user.UserID into a from join1 in a join group in db.Groups on join1.GroupID equals group.GroupID into b from join2 in b join entry in db.Entries.DefaultIfEmpty() on join2.GroupID equals entry.GroupID select entry ); Group last_group_id = 0; foreach(GroupEntry entry in entries) { if (last_group_id == 0 || entry.GroupID != last_group_id) { last_group_id = entry.GroupID; System.Console.WriteLine("---{0}---", entry.Group.GroupName.ToString().ToUpper()); } if (entry.EntryID) { System.Console.WriteLine(" {0}: {1}", entry.Title, entry.Text); } } } The example above does not work quite as expected. There are 2 problems that I have not been able to solve: I still seem to be getting an INNER JOIN instead of a LEFT JOIN on the last join. I am not getting any empty results, so groups without entries do not appear. I need to figure out a way so that I can fill in the default values for blank sets of entries. That is, if there is a group without an entry, I would like to have a mostly blank entry returned, except that I'd want the EntryID to be null or 0, the GroupID to be that of of the empty group that it represents, and I'd need a handle on the entry.Group object (i.e. it's parent, empty Group object). Any help on this would be greatly appreciated. Note: Table names and real-world representation were derived purely for this example, but their relations simplify what I'm trying to do.

    Read the article

  • left join on linq

    - by ognjenb
    SQL: FROM `order` o LEFT JOIN person d ON o.`DistributorId` = d.`Id` LEFT JOIN person c ON o.`CustomerId` = c.Id LEFT JOIN Transporter t ON o.`TransporterId` = t.Id LEFT JOIN IbekoEngineer e ON o.OrderEnteredBy = e.Id In any way to translate this 4 left join to LINQ query

    Read the article

  • How do I avoid a repetitive subquery JOIN in SQL?

    - by Karl
    Hi In SQL Server 2008: I have one table, and I want to do something along the following lines: SELECT T1.stuff, T2.morestuff from ( SELECT code, date1, date2 from Table ) as T1 INNER JOIN ( SELECT code, date1, date2 from Table ) as T2 ON T1.code = T2.code and T1.date1 = T2.date2 The two subqueries are exactly identical. Is there any way I can do this without repeating the subquery script? Thanks Karl

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >