gpt4 book ai didi

mysql - 在 MySQL 中使用连接查询链接表

转载 作者:行者123 更新时间:2023-11-29 02:01:01 29 4
gpt4 key购买 nike

我的架构如下:http://acookson.org/wp-content/uploads/bookings.png

enter image description here

我正在尝试使用连接提取唯一记录。假设“bob”在“2013-02-05 13:50:01”进行了预订booking.id=6。如何查询、加入和搜索类(class)表中的唯一记录?

我的表中填充了一些数据:

mysql> SELECT * from user; 
+----+--------+-----------------+
| id | name | email |
+----+--------+-----------------+
| 1 | bob | bob@spam.com |
| 3 | sarah | sj@global.com |
| 4 | phil | pj2@arpanet.com |
| 5 | freda | freda@gmail.com |
| 6 | Sash | s@yahoo.com |
| 7 | Glen | glen@global.com |
| 8 | Walter | w@arpanet.com |
+----+--------+-----------------+
7 rows in set (0.00 sec)

mysql> SELECT * from booking;
+----+---------------------+---------+
| id | date | user_id |
+----+---------------------+---------+
| 1 | 2013-02-08 12:28:24 | 1 |
| 4 | 2013-02-07 12:42:02 | 3 |
| 5 | 2013-02-05 12:42:46 | 4 |
| 6 | 2013-02-05 13:50:01 | 1 |
| 7 | 2013-02-01 13:50:01 | 3 |
| 8 | 2013-02-06 13:50:01 | 3 |
| 9 | 2013-01-29 13:50:01 | 4 |
+----+---------------------+---------+
7 rows in set (0.00 sec)

mysql> select * from lesson;
+----+-----------------------------+---------------------+---------------------+
| id | name | start_time | end_time |
+----+-----------------------------+---------------------+---------------------+
| 2 | CBT course | 2013-02-08 12:35:36 | 2013-02-08 13:35:36 |
| 3 | CBT course | 2013-02-15 11:59:44 | 2013-02-15 12:59:44 |
| 4 | Advanced Motorcyling module | 2013-02-15 12:04:29 | 2013-02-15 13:04:29 |
| 5 | CBT course | 2013-02-15 12:14:27 | 2013-02-15 13:14:27 |
| 6 | ABC course | 2013-02-13 13:28:13 | 2013-02-13 14:28:13 |
| 7 | LKU course | 2013-02-11 13:28:13 | 2013-02-11 14:28:13 |
| 8 | ERT starter course | 2013-02-10 13:28:13 | 2013-02-10 14:28:13 |
+----+-----------------------------+---------------------+---------------------+
7 rows in set (0.00 sec)

我的

lesson_booking
table is defined to reduce redundancy and it's this table thatI'm trying to query (indirectly) in order to return results.

My query looks like:

SELECT * from user as u
JOIN booking AS b ON b.id = u.id
JOIN lesson_booking AS lb ON b.id = lb.booking_id
JOIN lesson AS l ON lb.lesson_id = l.id
WHERE u.name = 'bob';
Empty set (0.00 sec)

但这不会返回任何结果。我对 MySQL 很基础,所以正在寻找一些例子我可能会如何真正查询此架构。

如果你能给我提供几个(三个就可以——不同的)例子来说明我可能会如何查询这个数据集那将是一种教育 - 我希望!

最佳答案

您很接近——查看您的预订加入——使用 user_id 而不是 id。它不应该是 b.id = u.id(这将您的用户 ID 加入您的预订 ID),而是 b.user_id = u.id:

SELECT * 
FROM user as u
JOIN booking AS b ON b.user_id = u.id
JOIN lesson_booking AS lb ON b.id = lb.booking_id
JOIN lesson AS l ON lb.lesson_id = l.id
WHERE u.name = 'bob';

祝你好运。

关于mysql - 在 MySQL 中使用连接查询链接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775395/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com