cari

Rumah  >  Soal Jawab  >  teks badan

SQL - Pertanyaan Gabungan Dalaman Asas

Saya mempunyai 3 MySQL jadual dan saya mahu menyertainya bersama-sama.


Kursus:

CREATE TABLE `library_classes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

INSERT INTO `library_classes` (`id`, `name`) VALUES
(1, 'Tolkien'),
(2, 'CS Lewis');

Perbualan:

CREATE TABLE `library_sessions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `class_id` int NOT NULL,
  `session_timestamp` timestamp NOT NULL,
  PRIMARY KEY (`id`),
  KEY `class_id` (`class_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

INSERT INTO `library_sessions` (`id`, `class_id`, `session_timestamp`) VALUES
(1, 1,  '2023-08-01 15:30:00'),
(2, 2,  '2023-08-02 10:15:00'),
(3, 1,  '2023-08-04 09:30:00');

Tempahan:

CREATE TABLE `library_bookings` (
  `id` int NOT NULL AUTO_INCREMENT,
  `session_id` int NOT NULL,
  `email` varchar(255) NOT NULL,
  `datetime_submitted` timestamp NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

INSERT INTO `library_bookings` (`id`, `session_id`, `email`) VALUES
(1, 1,  'jose@gmail.com'),
(2, 2,  'jane@yahoo.com'),
(3, 2,  'john@hotmail.com');

Apabila jose@gmail.com dilog masuk, saya mahu halaman saya kelihatan seperti ini:

Tolkien | 2023-08-01 15:30:00 | CANCEL
CS Lewis | 2023-08-02 10:15:00 | BOOK NOW
Tolkien | 2023-08-04 09:30:00 | BOOK NOW

P粉959676410P粉959676410459 hari yang lalu568

membalas semua(1)saya akan balas

  • P粉060528326

    P粉0605283262023-09-12 00:39:00

    Saya mengimport data anda ke dalam SQLFIDDLE;

    Pertanyaan berikut akan memberi anda hasil yang diharapkan.

    select lc.name, ls.session_timestamp,
    if(lb.id is null, 'BOOK NOW', 'CANCEL') as booking_status
    from library_classes lc
    join library_sessions ls on lc.id = ls.class_id
    left join library_bookings lb on ls.id = lb.session_id and lb.email = 'jose@gmail.com'
    order by ls.session_timestamp;

    Keluaran yang diharapkan ia berikan ialah:

    name        session_timestamp       booking_status
    Tolkien     2023-08-01T15:30:00Z    CANCEL
    CS Lewis    2023-08-02T10:15:00Z    BOOK NOW
    Tolkien     2023-08-04T09:30:00Z    BOOK NOW

    balas
    0
  • Batalbalas