Skip to content
Advertisement

I want to select all the data specified from multiple tables, but it only select one data

I have written a SQL query through which I want to select all the related data specified from multiple tables but when I run the query it only retrieve single data but I want to select all the data. Here is my query:

    $mysqli->query("SELECT projectDescription, location,budget,date, 
    SUM(ebudget) as expense_budget, SUM(totalAmount) as overtime_budget, 
    SUM(totalPrice) as material_budget FROM projecttable, expensestable, 
    overtimetable,dailyworkusage WHERE 
    expensestable.projectID=projecttable.projectID AND 
    overtimetable.projectID=projecttable.projectID AND 
    dailyworkusage.projectID=projecttable.projectID") or die($mysqli- 
    >error());

Advertisement

Answer

That’s because you are missing a GROUP BY clause (in non-ancient versions of MySQL, you would have met a syntax error). Add this at the end of your query:

GROUP BY projectDescription, location, budget, date

Also, you do want to use explicit joins instead of old-school, implicit joins. Using aliases for table names is also a good practice. Here is an updated version of your query:

SELECT 
    projectDescription, 
    location,
    budget,
    date, 
    SUM(ebudget) as expense_budget, 
    SUM(totalAmount) as overtime_budget, 
    SUM(totalPrice) as material_budget 
FROM projecttable p
INNER JOIN expensestable e ON e.projectID = p.projectID  
INNER JOIN overtimetable o ON o.projectID = p.projectID 
INNER JOIN dailyworkusage d ON d.projectID = p.projectID
GROUP BY 
    projectDescription, 
    location,
    budget,
    date

Please add the relevant table prefixes to all these columns (it cannot be told without seeing your actual table structures, that you did not show).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement