簡體   English   中英

來自多個表的SQL行

[英]SQL rows from multiple tables

我有一張代表清單的表格

id  |  item_type  |  item_id
----------------------------
1      'article'     24
2      'post'        9
3      'article'     120
4      'image'       9

item_type基本上表示該行假定為哪個表,id是該表中的id。 這意味着例如第二行和第四行不一樣。

我想讓我們說item_title和更多列將根據每個表以不同的方式創建。
假設如果item_type ='article',則item_title =該表中的title。
但是如果item_type是'image',則item_title = author_first_name + author_second_name + image_id
等等...

我正在谷歌搜索它或如何接近它。 特別是我以為我可以通過sql來解決if子語句的語句,但到目前為止還無法取得真正的進展。 所以我想請求幫助或指出正確的方向。

盡管接受的答案是准確且相對簡潔的,但它也很費力。 (即使結果被丟棄, article表也​​會連接到postimage行。)

為了改善這一點,你可以從...開始

select
    i.*,
    case 
      when i.item_type = 'article' then a.title
      when i.item_type = 'post'    then p.post_title
      when i.item_type = 'image'   then g.author_first_name + g.author_second_name + g.image_id
    end as item_title
  from item i
  left join article a on i.item_id = a.id AND i.item_type = 'article'
  left join post    p on i.item_id = p.id AND i.item_type = 'post'
  left join image   g on i.item_id = g.id AND i.item_type = 'image'

然而,許多優化者並不喜歡這樣。 如果你真的想要充分利用數據庫,我會在item(item_type)上放一個索引,然后為每個類型使用顯式邏輯......

   SELECT i.*, a.title
     FROM item i
LEFT JOIN article a ON i.item_id = a.id
    WHERE i.item_type = 'acticle'

UNION ALL

   SELECT i.*, p.post_title
     FROM item i
LEFT JOIN post p ON i.item_id = p.id
    WHERE i.item_type = 'post'

UNION ALL

   SELECT i.*, g.author_first_name + g.author_second_name + g.image_id
     FROM item i
LEFT JOIN image g ON i.item_id = g.id
    WHERE i.item_type = 'image'

更長時間的纏繞,但更加明確和優化友好。

您可以對所有這些表執行OUTER JOIN並使用適當的列組成標題,如下所示:

select
    i.*,
    case 
      when i.item_type = 'article' then a.title
      when i.item_type = 'post'    then p.post_title
      when i.item_type = 'image'   then
        g.author_first_name + g.author_second_name + g.image_id
    end as item_title
  from item i
  left join article a on i.item_id = a.id
  left join post    p on i.item_id = p.id
  left join image   g on i.item_id = g.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM