SQL联合从单行

时间:2015-03-12 09:10:37

标签: mysql union

我正试图将一行合并到自己身上。 数据库有一个包含大量列(48列)的表,我想对它进行分组,以便您可以查看结果列。

数据库如下所示:

表:RACEBETS

    RACENO|BETTER1|BET1|STAT1|BETTER2|BET2|STAT2|BETTER3|BET3|STAT3|BETTER4|...
    R01   |BT1    |200 |1    |BT2    |500 |1    |BT3    |500 |0    |BT4    |...

我目前有这个查询:

SELECT 
    ITEMS.ITEM43, ITEMS.ITEM44, ITEMS.ITEM45, ITEMS.ITEM46
FROM 
    (SELECT 
         'TYPE1' AS ITEM43, RACEBETS.BETTER1 AS ITEM44, 
         COALESCE(RACEBETS.BET1,'0') AS ITEM45, 
         COALESCE(RACEBETS.STAT1,'0') AS ITEM46, 
         RACEBETS.RACENO, '1' AS ORD 
     FROM 
         RACEBETS 
     WHERE 
         RACEBETS.BETTER1 IS NOT NULL

     UNION

     SELECT 
         'TYPE1' AS ITEM43, RACEBETS.BETTER2 AS ITEM44, 
         COALESCE(RACEBETS.BET2,'0') AS ITEM45, 
         COALESCE(RACEBETS.STAT2,'0') AS ITEM46, 
         RACEBETS.RACENO, '2' AS ORD 
     FROM 
         RACEBETS 
     WHERE 
         RACEBETS.BETTER2 IS NOT NULL

     UNION 

     SELECT 
         'TYPE2' AS ITEM43, RACEBETS.BETTER3 AS ITEM44, 
          COALESCE(RACEBETS.BET3,'0') AS ITEM45, 
          COALESCE(RACEBETS.STAT3,'0') AS ITEM46, 
          RACEBETS.RACENO, '3' AS ORD 
      FROM 
          RACEBETS 
      WHERE 
          RACEBETS.BETTER3 IS NOT NULL

      UNION
         some more... ) ITEMS, SCHEDULE
INNER JOIN 
    RACE ON SCHEDULE.SCHEDCODE = RACE.SCHEDCODE
WHERE 
    SCHEDULE.SCHEDCODE = '01'
    AND RACE.RACENO = '001'
    AND ITEMS.RACENO = RACE.RACENO
ORDER BY 
    ITEMS.ORD ASC

这显示了我想要的输出:

    ITEM43|ITEM44|ITEM45|ITEM46
    TYPE1 |BT1   |200   |1
    TYPE1 |BT2   |500   |1
    TYPE2 |BT3   |500   |0
    TYPE2 |.....

我相信我的当​​前查询将在联合之前检索所有行,并且会导致数据库变慢。

问题:

  1. 是否有单一选择联合的技巧,因为我将从单个选择中检索所有必需的文件?

  2. 如果我添加" where子句"它会更有效吗?和"加入条款"在使用union之前进入单独的select语句?

  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

我不认为这比你正在做的更好,但它确实只是从一个来自赛马场的SELECT进行操作。

SELECT thebets.ITEM44,thebets.ITEM45,thebets.ITEM46
 FROM
(
SELECT
    CONCAT('TYPE',map.item) ITEM44,

CASE map.item
    WHEN '1' THEN
        racebets.better2  
    WHEN '2' THEN
        racebets.better3  
    END AS betkey,
CASE map.item
    WHEN '1' THEN
        COALESCE(RACEBETS.BET2,'0') 
    WHEN '2' THEN
        COALESCE(RACEBETS.BET3,'0')
    END AS ITEM45,  
CASE map.item
    WHEN '1' THEN
        COALESCE(RACEBETS.STAT2,'0')
    WHEN '2' THEN
    COALESCE(RACEBETS.STAT3,'0')
    END AS ITEM46

from racebets 
join (
    select '1' item
    union all
    select '2'
) map
) thebets
WHERE thebets.betkey IS NOT NULL

'''我几天前从SO拿起来,但现在找不到帖子了。它连接到派生表,该表用作映射以取消结果。