SQL查询INNER JOIN - 意外结果

时间:2016-05-04 05:50:02

标签: php mysql sql sql-server

我有桌子:

  1. 旅行:Trip_Num,Trip_Type,Trip_Geographic等。

  2. travelers_trips_history:用户名,Trip_Num,Trip_Type,Trip_Season等。

  3. 在表2中,用户进行了旅行,我需要知道旅行历史中最常见的Trip_Geographic(表1中需要知道Trip_Geographic - 他的Trip_Num旅行)。 / p>

    我正在用PHP做一个项目,并且需要为特定用户(通过他的用户名)执行SQL查询 - 需要接收列为以下列的表:1。Trip_Geographic,Trip_Geographic在其中出现的计数travelers_trips_history。

    附上我的表格:

    trips

    travelers_trips_history
    travelers_trips_history

    我做的查询:

    $query = "select traveler_trips_history.*, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence 
    FROM traveler_trips_history INNER JOIN trips ON 
    travelers_trips_history.Trip_Num = trips.Trip_Num 
    GROUP BY Trip_Geographic 
    ORDER BY Trip_Geographic_occurrence DESC
    WHERE traveler_trips_history.Traveler_Username = $username";
    

    我收到有关Group BY的错误(检查语法),但是,我不确定查询是否会执行它应该执行的操作。

4 个答案:

答案 0 :(得分:3)

试试这个

    SELECT traveler_trips_history.*
    ,COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history
INNER JOIN trips ON travelers_trips_history.Trip_Num = trips.Trip_Num
WHERE traveler_trips_history.Traveler_Username = $USERNAME
GROUP BY traveler_trips_history.travelers_trips_history
    ,traveler_trips_history.Username
    ,traveler_trips_history.Trip_Num
    ,traveler_trips_history.Trip_Type
    ,traveler_trips_history.Trip_Season
ORDER BY Trip_Geographic_occurrence DESC

答案 1 :(得分:2)

您的查询中有2个问题:

1-您应该在GroupBy子句之前有where子句

2-如果您是GroupBy Col1,则只能选择Col1或在其他列上使用聚合函数(SUM,AVG等等)

您需要查看Rules for GroupBy并更好地了解它。

在评论后修改:

$query = "select Trip_Geographic, COUNT(*) AS Trip_Geographic_occurrence 
FROM traveler_trips_history INNER JOIN trips ON 
travelers_trips_history.Trip_Num = trips.Trip_Num 
WHERE traveler_trips_history.Traveler_Username = $username
GROUP BY Trip_Geographic 
ORDER BY Trip_Geographic_occurrence DESC";

答案 2 :(得分:0)

试试这个

问题是你的where子句和按列分组。

     SELECT tr.Trip_Geographic
    ,COUNT(hs.*) AS Trip_Geographic_occurrence
FROM traveler_trips_history hs
INNER JOIN trips tr ON hs.Trip_Num = tr.Trip_Num
WHERE hs.Username = $USERNAME
GROUP BY tr.Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC

答案 3 :(得分:0)

您的问题是GROUP By之后的Haing WHERE子句并使用不在GROUPED BY或AGGREGATE函数中的列。 尝试以下具有用户名,trip_geographic和旅行次数的。

select traveler_trips_history.Traveler_Username, traveler_trips_history.Trip_Geographic, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence 
FROM traveler_trips_history INNER JOIN trips ON 
travelers_trips_history.Trip_Num = trips.Trip_Num 
GROUP BY Trip_Geographic, traveler_trips_history.Traveler_Username
having traveler_trips_history.Traveler_Username = $username
ORDER BY Trip_Geographic_occurrence DESC