我想从多个表中选择所有指定的数据,但只选择一个数据

时间:2019-10-12 18:34:51

标签: php sql

我编写了一个SQL查询,通过该查询我想从多个表中选择所有指定的相关数据,但是当我运行查询时,它只检索单个数据,但我想选择所有数据。这是我的查询:

    $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());

1 个答案:

答案 0 :(得分:1)

那是因为您缺少一个GROUP BY子句(在非古代版本的MySQL中,您会遇到语法错误)。在查询末尾添加以下内容:

GROUP BY projectDescription, location, budget, date

此外,您确实希望使用显式联接而不是老式的隐式联接。对表名使用别名也是一种好习惯。这是查询的更新版本:

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

请在所有这些列中添加相关的表前缀(如果没有看到您未显示的实际表结构,则无法告知。)