MySql查询多个表,多对多,外键,需要获取与表中的搜索关联的表行

bq3bfh9z  于 2023-01-01  发布在  Mysql
关注(0)|答案(1)|浏览(106)

我有多个表:

我需要找其他演员和"杜约翰"演同一部电影
我试过很多方法,这是最后一次

select video.id,video.title, actor.name,  @act_id := x.actor_id, y.actor_id
from actor
join video_actor x on actor.id = x.actor_id
join video_actor y on actor.id = y.actor_id and y.video_id = x.video_id
join video ON x.video_id = video.id
where actor.name = 'John Doe' or (y.actor_id <> @act_id)

I am unable to figure out how to put together a query that will give me the other actors when I specify where actor.name = 'John Doe'
使用优秀的答案由Atmo我得到了正确的数据使用:

select video.id, video.title, GROUP_CONCAT(resultActor.name), GROUP_CONCAT(y.actor_id)
from actor queriedActor
join video_actor x on queriedActor.id = x.actor_id
join video_actor y on y.video_id = x.video_id
join actor resultActor on resultActor.id = y.actor_id
join video ON x.video_id = video.id
where queriedActor.name = 'Stacy Cruz'
GROUP BY video.id, video.title;

然后在我的应用程序中,完整的数据要求:

select video.id, video.title, GROUP_CONCAT(DISTINCT y.actor_id) as actors_id, GROUP_CONCAT(DISTINCT resultActor.name) as actors,producer.id,producer.name, GROUP_CONCAT(genre.name) as genres, MAX(pic.url) as cover
from actor queriedActor
join video_actor x on queriedActor.id = x.actor_id
join video_actor y on y.video_id = x.video_id
join actor resultActor on resultActor.id = y.actor_id
join video ON x.video_id = video.id
join producer ON video.producer_id = producer.id
join video_pic ON video.id = video_pic.video_id
join pic ON video_pic.pic_id = pic.id
join video_genre ON video.id = video_genre.video_id
join genre ON video_genre.genre_id = genre.id
where queriedActor.name = 'Stacy Cruz'
GROUP BY video.id, video.title,pic.cover
ORDER BY pic.cover DESC;
piztneat

piztneat1#

在前2个联接和where子句中,您写道:actor.id = x.actor_id = y.actor_id = <id of actor John Doe>.
您需要的是x.actor_id有机会与y.actor_id不同,就像您对video_actor所做的那样,您需要多次包含您的actor表。

select video.id, video.title, resultActor.name, y.actor_id
from actor queriedActor
join video_actor x on queriedActor.id = x.actor_id
join video_actor y on y.video_id = x.video_id
join actor resultActor on resultActor.id = y.actor_id
join video ON x.video_id = video.id
where queriedActor.name = 'John Doe'

或者,如果您需要与John Doe在同一部电影中的演员,而不是John Doe本人,请执行以下操作:

join video_actor y on y.video_id = x.video_id and y.actor_id <> x.actor_id

where queriedActor.name = 'John Doe' and resultActor.name <> 'John Doe'

相关问题