Mysql

選擇所有欄位(如果欄位不存在,則將欄位設為空值)

  • May 28, 2021

我有一個包含此欄位和條件的表格

table cc_queue_detail
ticket_id    field_name_id             data_content
1            category_ticket_1         33
1            category_ticket_2         44
2            category_ticket_1         55

我想為表 cc_queue_detail 選擇並將它們變成這樣:

ticket_id   category_ticket_1    category_ticket_2
1           33                   44
2           55 

我已經嘗試過這個查詢,但它只選擇了ticket_id 1

SELECT DISTINCT
a1.ticket_id AS 'ticket_id',
a2.data_content AS 'category_ticket_1',
a3.data_content AS 'category_ticket_2'
FROM 
cc_queue_detail a1
JOIN cc_queue_detail a2 ON a1.ticket_id = a2.ticket_id
JOIN cc_queue_detail a3 ON a1.ticket_id = a3.ticket_id
WHERE a2.field_name_id = "category_ticket_1"
AND a3.field_name_id = "category_ticket_2"

結果查詢:

ticket_id   category_ticket_1    category_ticket_2
1           33                   44

我嘗試更改 AND a3.field_name_id = "category_ticket_2"OR a3.field_name_id = "category_ticket_2",但它不起作用。

有人可以幫我解決這個問題嗎?

您的問題是您在相同的表之間使用INNER JOIN(簡稱) ,以及來自表的第二個和第三個實例的兩組不同的行,並且. 這基本上是說必須在,和always之間匹配,但是由於您的子句,這是不可能的,因為and是表中不同的行集。JOIN``ticket_id``cc_queue_detail``a1``cc_queue_detail``a2``a3``ticket_id``a1``a2``a3``WHERE``a2``a3``cc_queue_detail

你會想使用一個OUTER JOIN,比如LEFT OUTER JOINLEFT JOIN簡稱)來實現你的目標,像這樣:

SELECT DISTINCT
   a1.ticket_id AS 'ticket_id',
   a2.data_content AS 'category_ticket_1',
   a3.data_content AS 'category_ticket_2'
FROM cc_queue_detail a1
LEFT JOIN cc_queue_detail a2 
   ON a1.ticket_id = a2.ticket_id
   AND a2.field_name_id = "category_ticket_1"
LEFT JOIN cc_queue_detail a3 
   ON a1.ticket_id = a3.ticket_id
   AND a3.field_name_id = "category_ticket_2"

a1現在,您將從、整個表中取回所有行cc_queue_detail,並且在表的其他實例之間不匹配的地方 (a2a3) 將有NULL值。

AnOUTER JOIN在這裡可以很好地工作GROUP BY

SELECT a1.ticket_id,
      MAX(a2.data_content) AS category_ticket_1,
      MAX(a3.data_content) AS category_ticket_2
 FROM cc_queue_detail a1
      LEFT OUTER JOIN cc_queue_detail a2 ON a1.ticket_id = a2.ticket_id AND a2.field_name_id = 'category_ticket_1'
      LEFT OUTER JOIN cc_queue_detail a3 ON a1.ticket_id = a3.ticket_id AND a3.field_name_id = 'category_ticket_2'
GROUP BY a1.ticket_id

任何不存在的值都將返回為NULL.

引用自:https://dba.stackexchange.com/questions/292339