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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog