簡體   English   中英

MySQL根據當前表中的單元格從另一個表中獲取多個值

[英]MySQL get multiple values from another table based on cells in current table

我在查詢中尋求幫助,我有兩個表:

表格1:

id, version, icon1id, icon2id, icon3id, icon4id, icon5id
1   1        1        2        3        2        3
2   1        2        3        4        3        2
3   1        3        4        3        4        2
4   1        4        5        2        2        1

表2:

id, version, iconid, iconname
1   1        1       red
2   1        2       blue
3   1        3       green
4   1        4       purple
5   1        5       yellow
6   2        1       red
7   2        2       purple
8   2        3       blue
9   2        4       yellow
10  2        5       green

我想在表1上運行查詢,該查詢顯示如下內容:

id, version, icon1name, icon2name, icon3name, icon4name, icon5name
1   1        red        blue       green      blue       green

基本上,我希望編寫一個查詢,該查詢使用表1中的'version'和'iconid'並從表2中為它們中的每個返回匹配的'iconname'。我花了一些時間來尋找可以幫助但我正在努力將要正確搜索的內容充分投入工作...

任何幫助將不勝感激!

謝謝

兩種不處理row-> columns的任意數量的方法:

  1. 加入

    從左側的圖標中選擇table1.id,table1.version,icon1.iconname,icon2.iconname作為table1.version = icon1.version上的icon1加入table2,並將table1.iconid1 =左側的table1.iconid加入icon2作為table1.version = icon2上的icon2 .version和table1.iconid2 = icon2.iconid ...;

  2. 選擇中選擇(丑陋)

    選擇ID,版本,(從table2中選擇圖標名,其中version =版本,iconid = iconid1),(從table2中選擇圖標名,其中version =版本,iconid = iconid2),...,從table1中選擇;

我同意馬克B的意見 我也相信,這就是解決問題的方式。 另外,您可以嘗試以下查詢。 您必須為其他列添加其他聯接。

select table1.id, table1.version, icon1.iconname, icon2.iconname, icon3.iconname from table1
left join
table2 icon1
on table1.version = icon1.version
and table1.icon1id = icon1.iconid 
left join
table2 icon2
on table1.version = icon2.version
and table1.icon2id = icon2.iconid 
left join
table2 icon3
on table1.version = icon3.version
and table1.icon3id = icon3.iconid 
order by table1.id 

暫無
暫無

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

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