[英]SQL Query INNER JOIN - unexpected results
我有桌子:
行程:Trip_Num,Trip_Type,Trip_Geographic等。
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
我做的查询:
$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.