如何在MYSQL中连接具有相同实例的相同表?

时间:2017-04-03 08:11:56

标签: mysql sql

假设我在MYSQL中有以下表格

Sailors (sid,sname,rating,age) where sid-> Sailor's id, 

Reserves (sid,bid,day) where bid-> boat's id

我的查询是: -

  

查找在同一天航行两艘不同船只的水手的名字?

首先,我尝试加入两张保留表副本,并添加一个条件,即出价必须不同。

SELECT * FROM reserves R1,reserves R2 WHERE R1.day = R2.day AND R1.bid <> R2.bid;

我有这样的输出: -

enter image description here

现在,查询需要names of the sailors,因此我必须使用此结果表加入水手表。

现在,我如何应用join(条件是什么)操作来获得所需的结果?

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT *,s.SName As SailorName 
FROM reserves R1
INNER JOIN reserves R2 ON R1.day = R2.day AND R1.bid <> R2.bid
INNER JOIN Sailors s ON R2.sid = s.sid

答案 1 :(得分:0)

drop table if exists sailors;
drop table if exists reserves;

create table sailors(sid int, sname varchar(3));
create table reserves(bid int,sid int, dt date);

insert into sailors values
(1,'abc'),(2,'def'),(3,'ghi');
insert into reserves values
(100,1,'2017-01-01'),(200,1,'2017-01-01'),
(100,1,'2017-01-02'),(100,1,'2017-01-02'),
(100,2,'2017-01-01'),(100,2,'2017-01-01'),(300,2,'2017-01-01'),
(100,2,'2017-01-03'),(200,2,'2017-01-04')
;

select s.sid,t.sname,s.dt
        ,group_concat(s.bid order by s.bid) boats
from
(
select r.sid,r.dt,r.bid,
        if(concat(r.sid,r.dt,r.bid) <> @p, @rn:=1,@rn:=@rn+1) rn,       
         @p:=concat(r.sid,r.dt,r.bid) p
from   (select @rn:=0,@p:='') rn,reserves r
order by r.sid,r.dt,r.bid
) s
join sailors t on t.sid = s.sid
where s.rn = 1
group by s.sid,s.dt
having instr(boats,',') > 0

+------+-------+------------+---------+
| sid  | sname | dt         | boats   |
+------+-------+------------+---------+
|    1 | abc   | 2017-01-01 | 100,200 |
|    2 | def   | 2017-01-01 | 100,300 |
+------+-------+------------+---------+
2 rows in set (0.00 sec)

答案 2 :(得分:0)

您应该将表水手添加到 FROM 子句并添加条件:表 sailors 的两列 sid R1 相等。

尝试此查询:

SELECT *
FROM Reserves R1
INNER JOIN Reserves R2 ON R1.sid=R2.sid AND R1.bid<R2.bid AND R1.date=R2.date
INNER JOIN Sailors S ON R1.sid=S.sid

此外,我添加了必要的条件:您在查询中遗漏的R1.sid = R2.sid

相关问题