显示两组结果 - UNION不能正常工作

时间:2016-10-09 13:57:11

标签: mysql

我是MySQL的新手,我正在尝试检索两组结果以显示在同一页面上,一组在另一页之上。我已经设法让下面的UNION函数工作,它几乎'做我需要的东西,除了它结合在一个表中的结果。我希望第二个SELECT命令显示为第一个下面的独立表。那可能吗。到目前为止,这是我的代码:

    SELECT wp_wpdatatable_1.season,
   wp_wpdatatable_1.date,
   wp_wpdatatable_1.ha,
   wp_wpdatatable_1.competition,
   wp_wpdatatable_1.result,
   wp_wpdatatable_1.score,
   wp_wpdatatable_1.scorers
   FROM wp_wpdatatable_1
   WHERE 1=1 
   AND wp_wpdatatable_1.opponents = 'Everton'

   UNION 

    SELECT
    null AS count1,
    null AS count2,
    null AS count3,
    SUM(CASE WHEN opponents='Everton' THEN 1 ELSE 0 END) AS played,
    SUM(CASE WHEN result LIKE 'W' and opponents='Everton' THEN 1 ELSE 0 END) AS won,
    SUM(CASE WHEN result LIKE 'D' and opponents='Everton' THEN 1 ELSE 0 END) AS drawn,
    SUM(CASE WHEN result LIKE 'L' and opponents='Everton' THEN 1 ELSE 0 END) AS lost
    FROM wp_wpdatatable_1

1 个答案:

答案 0 :(得分:0)

你的意思是你想看到2个单独的列标题,在这种情况下不确定这在mySQL中是否可行?

但是,如果你只是想要一个接一个地想要行的顺序,添加一个你可以订购的虚拟列(并不是下面的必需,因为顺序将使记录唯一,但在你的使用中的良好做法例如,添加UNION ALL以避免每个文档消除重复的行http://dev.mysql.com/doc/refman/5.7/en/union.html

(SELECT wp_wpdatatable_1.season, wp_wpdatatable_1.date, wp_wpdatatable_1.ha, wp_wpdatatable_1.competition, wp_wpdatatable_1.result, wp_wpdatatable_1.score, wp_wpdatatable_1.scorers, 1 as table_order FROM wp_wpdatatable_1 WHERE 1=1 AND wp_wpdatatable_1.opponents = 'Everton' ) UNION ALL ( SELECT null AS count1, null AS count2, null AS count3, SUM(CASE WHEN opponents='Everton' THEN 1 ELSE 0 END) AS played, SUM(CASE WHEN result LIKE 'W' and opponents='Everton' THEN 1 ELSE 0 END) AS won, SUM(CASE WHEN result LIKE 'D' and opponents='Everton' THEN 1 ELSE 0 END) AS drawn, SUM(CASE WHEN result LIKE 'L' and opponents='Everton' THEN 1 ELSE 0 END) AS lost, 2 as table_order FROM wp_wpdatatable_1 ) ORDER BY table_order