簡體   English   中英

SQL查詢INNER JOIN-意外結果

[英]SQL Query INNER JOIN - unexpected results

我有桌子:

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

  2. Travellers_trips_history:用戶名,Trip_Num,Trip_Type,Trip_Season等。

在表2中,有用戶進行的旅行,我需要知道他的旅行歷史上最常見的Trip_Geographic(表1需要了解Trip_Geographic-他的Trip_Num進行的旅行)。

我正在用PHP執行一個項目,並且需要針對特定​​用戶(通過其用戶名)執行SQL查詢-需要接收一個表,這些表的列為:1. Trip_Geographic,Trip_Geographic在travellers_trips_history中出現的次數。

附上我有的表:
旅行
旅行

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(檢查語法)的錯誤,但是,我不確定查詢將執行應做的事情。

嘗試這個

    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

您的查詢中有2個問題:

1-您應該在GroupBy子句之前有where子句

2-如果對Col1進行分組,則只能選擇Col1或在其他列(SUM,AVG等)上使用聚合函數

您需要檢查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";

這樣嘗試

問題是您的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

您的問題是在GROUP BY之后使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM