我正在构建一个界面来连接表格并在 Retool 中提供有关我们代表客户销售的二手产品的信息。
我有几个表都与单个产品相关。其他表格是有关流程或状态的信息——即,送修、已售、已退回、卖方已付款。
我正在寻找一个表格,该表格提供按日期排序的产品历史记录。我可以加入所有表并获得单行数据,但我正在寻找一个垂直表,例如:
+--+-----------+---------------+
|id|Date |Status |
+--+-----------+---------------+
| 1| 2020-01-01|Booked in |
+--+-----------+---------------+
| 1| 2020-01-04|Sent for repair|
+--+-----------+---------------+
| 1| 2020-02-10|Sold |
+--+-----------+---------------+
| 1| 2020-02-28|Returned |
+--+-----------+---------------+
状态列将是由存在于哪个表中的信息确定的 CASE 语句。
此刻它更像
+--+-----------+---------------+-----------+---------------+-----------+---------------+
|id|Date |Status |Date |Status |Date |Status |
+--+-----------+---------------+-----------+---------------+-----------+---------------+
| 1| 2020-01-01|Booked in | 2020-01-01|Booked in | 2020-01-04|Sent for repair|
+--+-----------+---------------+-----------+---------------+-----------+---------------+
所以总而言之,有没有一种方法可以根据单个产品 ID 垂直连接多个表。
我希望这一切都有意义,如果有什么需要澄清的,我会尽力而为。
提前致谢
相关表格/数据如下:
CREATE DATABASE StackOverflow_test;
USE StackOverflow_test;
CREATE TABLE commission_sales
(
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
created_at TIMESTAMP DEFAULT NOW(),
product VARCHAR(20)
);
CREATE TABLE sold_data
(
id INT AUTO_INCREMENT PRIMARY KEY,
comm_no INT,
final_price DECIMAL(8,2),
sale_date DATE,
sale_ref VARCHAR(20),
created_at TIMESTAMP DEFAULT NOW(),
FOREIGN KEY (comm_no)
REFERENCES commission_sales(id)
);
CREATE TABLE returned_from_buyer
(
id INT AUTO_INCREMENT PRIMARY KEY,
comm_no INT,
returned_date DATE,
returned_notes VARCHAR(255),
FOREIGN KEY (comm_no)
REFERENCES commission_sales(id)
);
CREATE TABLE returned_to_seller
(
id INT AUTO_INCREMENT PRIMARY KEY,
comm_no INT,
returned_date DATE,
returned_notes VARCHAR(255),
FOREIGN KEY (comm_no)
REFERENCES commission_sales(id)
);
CREATE TABLE additional_charges
(
id INT AUTO_INCREMENT PRIMARY KEY,
comm_no INT,
amount DECIMAL(8,2),
notes VARCHAR(250),
paid BOOL DEFAULT 0,
created_at TIMESTAMP DEFAULT NOW(),
FOREIGN KEY (comm_no)
REFERENCES commission_sales(id)
);
还有一些假数据:
INSERT INTO commission_sales
(id,customer_id,product,created_at)
VALUES (1,72,"Teddy Bear","2020-12-10")
;
INSERT INTO sold_data
(comm_no,final_price,sale_date,sale_ref)
VALUES (1,25.99,"2020-12-15","AGRJOWKO")
;
INSERT INTO returned_from_buyer
(comm_no,returned_date,returned_notes)
VALUES (1,"2020-12-29","Broken")
;
INSERT INTO returned_to_seller
(comm_no,returned_date,returned_notes)
VALUES (1,"2021-01-30","Customer is Idiot")
;
INSERT INTO additional_charges
(comm_no,amount,notes,paid,created_at)
VALUES (1,10,"repair",0,"2021-01-05")
;
一个基本的 JOIN 将所有数据放在一行上,但我希望数据垂直显示:
SELECT * FROM commission_sales
JOIN sold_data ON commission_sales.id = sold_data.comm_no
JOIN additional_charges ON commission_sales.id = additional_charges.comm_no
JOIN returned_from_buyer ON commission_sales.id = returned_from_buyer.comm_no
JOIN Returned_to_seller ON commission_sales.id = returned_to_seller.comm_no
;