子查询选择使用UNION

时间:2012-11-09 15:20:27

标签: mysql subquery union correlated-subquery

CREATE TABLE newsarticles
    (katernenID int, Buitenland int, Economie int, Sport int, Cultuur int, Wetenschap int, Media int, userID int);

INSERT INTO newsarticles
    (katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID)
VALUES
    (1, 24, 5, 52, 3, 2, 3, 1),
    (3, 2, 0, 0, 1, 51, 66, 5),
    (4, 50, 2, 67, 41, 1, 54, 6),
    (5, 30, 1, 79, 0, 0, 12, 7),
    (6, 9, 26, 0, 100, 11, 0, 8),
    (7, 2, 14, 8, 1, 33, 98, 9),
    (8, 0, 1, 0, 1, 0, 0, 10);



SELECT
  userID,GROUP_CONCAT(amt ORDER BY amt DESC) AS four_highest
FROM
(
  SELECT userID, @rownum := @rownum + 1 AS rank, NAME, amt FROM (
    SELECT userID, Buitenland AS amt, 'Buitenland' AS NAME UNION
    SELECT userID, Economie, 'Economie'  UNION
    SELECT userID, Sport, 'Sport' UNION
    SELECT userID, Cultuur, 'Cultuur'  UNION
    SELECT userID, Wetenschap, 'Wetenschap'  UNION
    SELECT userID, Media, 'Media' 
         FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp

  ) amounts, (SELECT @rownum := 0) r
) top4
GROUP BY userid

我想在上面的查询中使UNION,但是Union不工作。 UNION需要立即声明FROM语句。 像:

    SELECT userID, Wetenschap, 'Wetenschap'  
                 FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp
                 UNION
    SELECT userID, Media, 'Media' 
         FROM( SELECT katernenID, Buitenland, Economie, Sport, Cultuur, Wetenschap, Media, userID FROM newsarticles  ) temp

但是我不能重复FROM语句,子查询中有太多的计算。有没有办法做到这一点,还是我错过了什么?

OR

我想要一个包含max(a_percentage,b_percentage,c_percentage),SecondMAX(a_percentage,b_percentage,c_percentage),ThirdMAX(a_percentage,b_percentage,c_percentage)的新列

    SELECT id,a,b,c,a_percentage,b_percentage,c_percentage
    -- -------------------------max percentage
    GREATEST(axis_per, hdfc_per,icici_per,citi_per ) AS max_per,
    FROM (
      SELECT id,a,b,c,
      IFNULL(a*100/a+b+c+d,0) AS a_percentage,
      IFNULL(b*100/a+b+c+d,0) AS b_percentage,
      IFNULL(c*100/a+b+c+d,0) AS c_percentage
      FROM test
        WHERE TIME > '2012-01-01'
        GROUP BY id
      ) A

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您应该只能使用FROM中的表名,并在每行的别名上添加别名,例如:

SELECT
  userID,GROUP_CONCAT(amt ORDER BY amt DESC) AS four_highest
FROM
(
  SELECT userID, @rownum := @rownum + 1 AS rank, NAME, amt FROM (
    SELECT userID, Buitenland AS amt, 'Buitenland' AS NAME FROM newsarticles NAME UNION
    SELECT userID, Economie, 'Economie'  FROM newsarticles UNION
    SELECT userID, Sport, 'Sport'  FROM newsarticles UNION
    SELECT userID, Cultuur, 'Cultuur'  FROM newsarticles UNION
    SELECT userID, Wetenschap, 'Wetenschap'  FROM newsarticles UNION
    SELECT userID, Media, 'Media' FROM newsarticles
) amounts, (SELECT @rownum := 0) r
) top4
GROUP BY userid