2016-04-12 65 views
2

我有表:SQL查詢2頁不同的表

  1. 旅行:Trip_Num,Trip_Type等
  2. 用戶的旅行史:用戶名,Trip_Num等

我做了項目在PHP中,需要爲特定用戶(通過他的用戶名)做一個SQL查詢 - 需要知道用戶的旅程歷史表中的Trip_Num的Trip_Type。

附我有表:

旅行

enter image description here

用戶的旅行史

enter image description here

更新: 我需要對Trip_type中的每個值進行計數。我的意思是我想看到「徒步」 - 4次出現,「自行車」 - 3次出現,這很好嗎?......................... ..................................................選擇Trips_History *,Trips.Trip_Type,COUNT(Trip_Type)AS Trip_Type_occurrence TRIPS協定歷史INNER JOIN BY Trip_Type量級Trips_History.Trip_Num = Trips.Trip_Num團體旅行BY Trip_Type_occurrence DESC -

+0

一下這個http://www.w3schools.com/ sql/sql_join.asp – Jkidd93

回答

0

一個簡單JOIN會做。

SELECT 
    th.*, 
    t.Trip_Type 
FROM Trip_History AS th 
INNER JOIN Trips AS t 
    ON t.Trip_Num = th.Trip_Num 
0

試試這個:

select Trips_History.*,COUNT(Trips.Trip_Type) AS Trip_Type_occurrence FROM Trips_History INNER JOIN Trips on Trips_History.Trip_Num = Trips.Trip_Num GROUP BY Trip_Type ORDER BY Trip_Type_occurrence DESC 
+0

謝謝。我需要對Trip_type中的每個值進行計數。我的意思是我想看到「徒步」 - 4次出現,「自行車」 - 3次出現,這很好嗎?......................... .................................................. ....................選擇Trips_History。*,Trips.Trip_Type,COUNT('Trip_Type')AS'Trip_Type_occurrence' FROM旅程歷史記錄INNER JOIN Trips_History.Trip_Num = Trips.Trip_Num GROUP BY Trip_Type ORDER BY Trip_Type_occurrence DESC –

0

試試這個

select t2.traveller_username,t1.Trip_Type from 
trips as t1 inner join trips_history as t2 on t1.Trip_num=t2.trip_num 
0

嘗試,

SELECT t.Trip_Type, u.Trip_Num from trips at t 
JOIN user_trips_history ON u.Trip_Num = t.Trip_Num 
WHERE u.Traveller_Username = 'username'; 
0

嘗試這樣做:

SELECT t.Trip_Type, u.Trip_Num FROM trips as t 
JOIN user_trips_history as u ON t.Trip_Num=u.Trip_Num 
WHERE u.Traveller_Username = 'USERNAME'; 
0

你可以試試這個 -

SELECT users_trip_history.trip_num, trips.trip_type, COUNT(trips.trip_type) AS trip_occurences 
FROM users_trip_history 
INNER JOIN trips 
ON users_trip_history.trip_num = trips.trip_num 
WHERE users_trip_history.traveler_username = "name" 
GRUOP BY trip_num; 
+0

好的,我已經編輯了我的答案。 –