SQL查询2个不同的表

时间:2016-04-12 07:02:51

标签: php mysql

我有桌子:

  1. 旅行:Trip_Num,Trip_Type等
  2. 用户的旅程历史:用户名,Trip_Num等
  3. 我在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 FROM Trips历史INNER JOIN Trips on Trips_History.Trip_Num = Trips.Trip_Num GROUP BY Trip_Type ORDER BY Trip_Type_occurrence DESC -

6 个答案:

答案 0 :(得分:0)

一个简单的JOIN会:

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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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';

答案 4 :(得分: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';

答案 5 :(得分: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;