mysql 5 表选择查询

发布于 2024-11-07 11:48:10 字数 225 浏览 0 评论 0原文

我有 5 个表:

  1. users
  2. Bands_users
  3. Bands
  4. Band_gigs
  5. gigs

一个用户可以有很多乐队,一个乐队可以有很多用户 一个演出可以有很多乐队,一个乐队可以有很多演出

给定用户 id 1,我想返回所有演出及其关联乐队。

任何帮助将不胜感激。

I have 5 tables:

  1. users
  2. bands_users
  3. bands
  4. bands_gigs
  5. gigs

A user can have many bands, a band can have many users
A gig can have many bands, a band can have many gigs

Given the user id 1, I would like to return all the gigs with their associated band.

Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白日梦 2024-11-14 11:48:10

像这样的东西?

SELECT g.*, b.*
FROM users u 
LEFT JOIN band_users bu ON u.id = bu.uid 
LEFT JOIN bands b ON bu.bid = b.id 
LEFT JOIN bands_gigs bg ON b.id = bg.bid 
LEFT JOIN gigs g ON bg.gid = g.id
WHERE u.id = 1

something like this?

SELECT g.*, b.*
FROM users u 
LEFT JOIN band_users bu ON u.id = bu.uid 
LEFT JOIN bands b ON bu.bid = b.id 
LEFT JOIN bands_gigs bg ON b.id = bg.bid 
LEFT JOIN gigs g ON bg.gid = g.id
WHERE u.id = 1
小忆控 2024-11-14 11:48:10

您可以在一行中完成此操作,但从简单开始,基本思想是首先将用户与 Bands_users 和 Bands 连接,其中用户 id 位于 users 和 Bands_users 中,并且 Band id 位于 Bands_users 和 Bands 中。这将为您提供用户所在乐队的列表。然后,您将乐队与 band_gigs 和 gigs 一起加入,其中乐队 id 既在 Bands 又在 Bands_gigs 中,而演出 ID 也在 Bands_gigs 和 gigs 中。现在您已获得用户所在乐队列表的演出列表。

You can do this in one line, but to start simple, the basic idea is that you first join users with the bands_users and bands where the user id is in both users and bands_users, and the band id is in both bands_users and bands. That will get you the list of bands a user is in. Then you join bands with bands_gigs and gigs where the band id is in both bands and bands_gigs, and the gig id is in both bands_gigs and gigs. Now you have the list of gigs for the list of bands that a user is in.

刘备忘录 2024-11-14 11:48:10

可以从以下几点开始:

SELECT band.name,
       gig.name
FROM   users
       JOIN bands_users
         ON users.name = bands_users.userName
       JOIN bands
         ON bands.name = bands_users.bandName
       JOIN bands_gigs
         ON bands.name = bands_gigs.bandName
       JOIN gigs
         ON bands_gigs.gigName = gigs.name
WHERE  users.id = 1; 

Something to start with:

SELECT band.name,
       gig.name
FROM   users
       JOIN bands_users
         ON users.name = bands_users.userName
       JOIN bands
         ON bands.name = bands_users.bandName
       JOIN bands_gigs
         ON bands.name = bands_gigs.bandName
       JOIN gigs
         ON bands_gigs.gigName = gigs.name
WHERE  users.id = 1; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文