douchibu7040 2011-01-12 12:24
浏览 1053
已采纳

MySQL将两个表中的两个字段合并到结果集中的一个字段中

Thank you for all the help I have received here and yet, here I'm with a complementary question.

Setup

I have 3 relevant tabels in MySQL:

STRINGVALUES
ID   ItemID   Key    Value
1    1        Note   My note book is electronica

INTEGERVALUES
ID   ItemID Key    Value
1    1      Color  2
2    1      Type   4

STRINGS
ID   Value
1    Stone
2    Red
3    Blue
4    Phone

Other fields has been removed to only show what is relevant. ItemID is the identifier for an Article. In this case I have only entered information for Article 1 (ItemID=1)

The INTEGERVALUES table uses the Value as an ID to lookup a value in the STRINGS table (hence a separate table with only integers). The strings table also have support for multiple languages while StringValues are data entered by users.

Desired result

The SQL query I have now looks like this:

SELECT i.*, ai.Key, ai.Value,
(SELECT s.Value FROM Strings s WHERE ai.Value=s.StringID) sValue,
(SELECT ats.Value FROM attributestrings ats WHERE ats.ItemID=i.ItemID) sValue
FROM items i
INNER JOIN AttributeIntegers ai ON i.ItemID=ai.ItemID
WHERE i.ID = 1

This gives me the relevant result

ItemID Key    Value  sValue  sValue
1      Color  2      Red     My note book is electronica
1      Type   4      Phone   My note book is electronica

What I want is this result:

ItemID Key    Value  sValue
1      Color  2      Red
1      Type   4      Phone
1      Note   Null   My note book is electronica

I'm trying to read up on UNION but I don't know if it is the right answer...

Thanks.

  • 写回答

2条回答 默认 最新

  • dsxjot8620 2011-01-12 12:28
    关注
    SELECT  *
    FROM    (
            SELECT  itemid, key, iv.value, s.value AS svalue
            FROM    integervalues iv
            JOIN    strings s
            ON      s.id = iv.value
            WHERE   iv.itemid = 1
            UNION ALL
            SELECT  itemid, key, NULL, value
            FROM    stringvalues sv
            WHERE   sv.itemid = 1
            ) vals
    JOIN    items i
    ON      i.id = vals.itemid
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记