Easier Query

Discussion in 'MySQL' started by debz89uk, Mar 27, 2010.

  1. #1
    I have lots of tables that I need to join/query at the one time.
    I have something like this :

    $sql = "SELECT
    		ProgrammingFoundations.student_id,
    		ProgrammingFoundations.total_PF_attendance,
    		InformationSystems.total_IS_attendance,
    		Machines.total_M_attendance
    		FROM
    		ProgrammingFoundations,
    		InformationSystems,
    		Machines
    		Where
    		ProgrammingFoundations.student_id = InformationSystems.student_id
    		and ProgrammingFoundations.student_id = Machines.student_id
    		and InformationSystems.student_id = Machines.student_id;
    Code (markup):
    Is there a simpler way to write
    	Where
    		ProgrammingFoundations.student_id = InformationSystems.student_id
    		and ProgrammingFoundations.student_id = Machines.student_id
    		and InformationSystems.student_id = Machines.student_id;
    
    Code (markup):
    As I have more tables I need to add to this query and there would be a LOT of ANDs.
     
    debz89uk, Mar 27, 2010 IP
  2. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #2
    By the transitive relation of your tables on the student_id field the 3rd line of your WHERE clause is redundant/unnecessary.

    If a=b and b=c, you don't need to state that a=c.

    All the where clause needs to say is

    
    	Where
    		ProgrammingFoundations.student_id = InformationSystems.student_id
    		and ProgrammingFoundations.student_id = Machines.student_id
    
    PHP:
     
    plog, Mar 27, 2010 IP
  3. mnvlxxx

    mnvlxxx Peon

    Messages:
    47
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    $sql = "SELECT
    		PF.student_id,
    		PF.total_PF_attendance,
    		IS.total_IS_attendance,
    		M.total_M_attendance
    		FROM
    		ProgrammingFoundations PF,
    		InformationSystems IS,
    		Machines M
    		Where
    		 PF.student_id = IS.student_id
    		and  PF.student_id = M.student_id;
    Code (markup):
     
    mnvlxxx, Mar 27, 2010 IP
  4. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #4
    $sql = "SELECT
    		ProgrammingFoundations.student_id,
    		ProgrammingFoundations.total_PF_attendance,
    		InformationSystems.total_IS_attendance,
    		Machines.total_M_attendance
    		FROM
    		ProgrammingFoundations JOIN
    		InformationSystems 
    		USING(student_id) JOIN
    		Machines
    		USING(student_id)";
    
    PHP:
    Regards :)
     
    koko5, Mar 27, 2010 IP