dongwolu5275 2012-07-13 20:27
浏览 7
已采纳

我想我需要自我加入?

I have a table with the following structure:

id, Metal, AmPm, GBP, USD, EUR, Updated, TimeStamp

Sample values include:

INSERT INTO `LondonFixes` (`id`, `Metal`, `AmPm`, `GBP`, `USD`, `EUR`, `Updated`, `TimeStamp`) VALUES
(228, 'Gold', 'AM', '1779.22000', '2748.00000', '2253.20000', '2012-07-13', '2012-07-13 15:19:35'),
(224, 'Gold', 'PM', '1022.33700', '1579.00000', '1294.05000', '2012-07-13', '2012-07-13 13:16:59'),

I have queried the data and am able to get the last 10 rows and order them how I want as follows:

    $r = mysql_query("SELECT * FROM(SELECT id, GBP, AmPm, Updated FROM LondonFixes WHERE Metal = 'Gold' AND UPDATED < now() ORDER BY id DESC LIMIT 10) AS src ORDER BY id ASC");

This returns a table of the form:

id, GBP, AmPm, Updated

The problem is that I need a table of the form:

id, GBP_AM, GBP_PM, Updated

Basically, AmPm values can either contain the values "AM" or "PM". I want to show the GBP value for both AM and PM on one line where updated is the same on both lines.

e.g. Required output based on above sample data:

1, 1779.22000, 1022.33700, 2012-07-13

I think that this is a self Join, but I just don't understand self joins and I am not even sure that Self Joins is what I need.

  • 写回答

2条回答 默认 最新

  • dongre1907 2012-07-13 20:42
    关注

    You don't need to incur the overhead of a self-join. Instead, simply do it with conditional checking:

    SELECT a.*
    FROM
    (
          SELECT MAX(CASE AmPm WHEN 'AM' THEN GBP END) AS GBP_AM,
                 MAX(CASE AmPm WHEN 'PM' THEN GBP END) AS GBP_PM,
                 Updated
            FROM LondonFixes
           WHERE Updated < CURDATE() AND Metal = 'Gold'
        GROUP BY Updated
        ORDER BY Updated DESC
           LIMIT 10
    ) a
    ORDER BY a.Updated
    

    This is assuming the id field is not important to you. I'm excluding it in my solution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路