从一个mysql表连接一行到第二个表中的多个行

时间:2015-01-14 11:30:34

标签: php mysql join

我对mysql查询有疑问。这个故事是这样的:我有一张桌子,里面有关于大学旅行的信息。该表具有关于旅行名称,旅行ID和活动的属性。活动可以是0或1,具体取决于行程是否仍然有效(1)或无效(0)。在第二个表格中,我有关于申请旅行的学生的信息:学生申请的旅行的身份证,姓名,姓名和身份证明。我不知道mysql查询,只会向我显示已申请仍然有效的旅行的学生(acitivity = 1)。

例如,让我们看一下这些表:

TRIPS

id | trip     | activity
---+----------+-----------
1  | Paris    | 0
2  | London   | 1
3  | Belgrade | 0
4  | Prague   | 1

STUDENTS

id | name     | id_trip
---+----------+-----------
1  | Mark     | 3
2  | Ana      | 1
3  | Tom      | 2
4  | Maya     | 3
5  | Rachel   | 4
6  | John     | 2



   RESULT

    id | name     | id_trip | trip    | activity
    ---+----------+---------+---------+---------
    3  | Tom      | 2       | London  | 1
    5  | Rachel   | 4       | Prague  | 1
    6  | John     | 2       | London  | 1

4 个答案:

答案 0 :(得分:0)

试试这个:

SELECT s.id, s.name, s.id_trip, t.name, t.activity
FROM students s
JOIN trips t
ON s.id_trip = t.id
WHERE t.activity = 1

答案 1 :(得分:0)

select * from students s
join trips t
on  s.id_trip = t.id
where t. activity =1

答案 2 :(得分:0)

SELECT 
s.id, 
s.name, 
s.id_trip, 
t.trip, 
t.activity
FROM 
STUDENTS AS s
INNER JOIN TRIPS AS t ON ( t.id = s.id_trip ) 
WHERE
t.id = 1
希望这会奏效。

答案 3 :(得分:0)

试试这可能会解决您的问题:

select s.id as id, s.name as name,t.trip as trip, 
t.activity as activity from trips t 
join  students s on 
t.id = s.id_trip 
where t.activity = 1
相关问题