Mysql
需要幫助來編寫查詢連接 3 個表
我有一個名為的表
form_submission_entries
,其中包含如下數據:field_id 對應的
form_fields
表如下所示:當然還有一個
form_submissions
看起來像這樣的表:我想執行一個查詢,它允許我創建一個如下所示的 CSV 文件:
我可以通過創建多個查詢來實現這一點。首先通過從
form_submissions
. 然後使用該 id 列表創建多個查詢以從form_submission_entries
使用submission_id
. 但它看起來很噁心。我希望某個地方的某個人會有更好的方法。非常感謝!
如果我了解您的架構和目標,您可以通過幾種不同的方式來實現這一目標。這是獲得所需輸出的一種方法:
SELECT FS.id AS submission_id, FirstName.value AS first_name, LastName.value AS last_name, Age.value AS age, FS.submitted_at FROM form_submissions FS LEFT JOIN form_submission_entries FirstName ON FS.id = FirstName.submission_id AND FirstName.field_id = 1 LEFT JOIN form_submission_entries LastName ON FS.id = LastName.submission_id AND LastName.field_id = 2 LEFT JOIN form_submission_entries Age ON FS.id = Age.submission_id AND Age.field_id = 3
該查詢應該是相當不言自明的,但本質上它從父
form_submissions
表開始並連接到子表form_submission_entries
三次,每次僅在特定條目上。我正在使用LEFT JOIN
(這是一個外連接),以防您的任何條目都不需要。如果它們都是必需的,並且對於給定的送出,所有三個都將始終存在,那麼您可以將 s 切換為LEFT JOIN
sINNER JOIN
。最後,要將上述 SQL 結果集轉換為 CSV 輸出,您只需
SELECT
使用逗號連接列表中的列,並在標題中合併,如下所示:SELECT CONCAT ( 'submission_id', ',', 'first_name', ',', 'last_name', ',', 'age', ',', 'submitted_at' ) UNION ALL SELECT CONCAT ( FS.id, ',', FirstName.value, ',', LastName.value, ',', Age.value, ',', FS.submitted_at ) FROM form_submissions FS LEFT JOIN form_submission_entries FirstName ON FS.id = FirstName.submission_id AND FirstName.field_id = 1 LEFT JOIN form_submission_entries LastName ON FS.id = LastName.submission_id AND LastName.field_id = 2 LEFT JOIN form_submission_entries Age ON FS.id = Age.submission_id AND Age.field_id = 3