如何在MYSQL中加入具有相同实例的相同表?在MYSQL
问题描述:
假设我有以下各表如何在MYSQL中加入具有相同实例的相同表?在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;
我得到的输出是这样的: -
现在,查询想要names of the sailors
,因此对我有加盟水手表这个结果表。
现在,我该如何应用连接(有什么条件)的操作来获得所需的结果?
答
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:[email protected]+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)
答
试试这个:
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
答
你应该添加表海员类FROM条款和补充条件:两列的表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您在查询
你的两个表的模型描述是不完整的错过。此外,加入r1和r2的查询可能应该加入'... AND R1.bid> R2.bid',以避免在无序元组上重复。 – Sebas
@ Sebas我应该提供表格的实例吗? – Barry
我的意思是,你的定义中似乎有些列缺失(例如储备中的日子列)。我想我们需要他们加入的目的,否则我不明白你怎么可以加入水手和储备一起 – Sebas