如何组合其他表中的列

时间:2016-01-29 07:10:56

标签: mysql

我创建了2个临时表:

--------------      ------------------
| withlabfee |      | without lab fee|
--------------      ------------------  
|   6        |      |       3        |
--------------      ------------------

我的代码使用单列返回以下结果。

-------------------------------
| withlabfee , without lab fee|
------------------------------- 
|   6        ,      3         |
------------------------------

我尝试的代码如下

    drop table if exists withlabFee;
    create temporary table withlabFee(labFee1 int);
    insert into withlabFee
        select count(*)
        from course_relation
        where lab_fee is not null;

    drop table if exists withoutLabfee;
    create temporary table withoutLabfee(labFee2 int);
    insert into withoutLabfee
        select count(*)
        from course_relation
        where lab_fee is null;

    select concat(labfee1,',',labfee2) as `With lab fee , Without lab fee`
    from withlabFee, withoutLabfee;

    drop table labFee;
    drop table withoutLabfee;

如何将我的临时表中的列withlabfee和withoutlabfee组合成1个表,其中包含2列,如下所示:

-------------------------------
| withlabfee | without lab fee|
------------------------------- 
|   6        |      3         |
-------------------------------

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

解决方案即使没有临时表:

SELECT
  SUM(lab_fee IS NOT NULL) AS 'With lab fee',
  SUM(lab_fee IS NULL) AS 'Without lab fee'
FROM 
  course_relation

答案 1 :(得分:0)

尝试以下查询(不创建临时表)。

SELECT 
COUNT(CASE WHEN lab_fee IS NOT NULL THEN 1 END) AS withlabFee,
COUNT(CASE WHEN lab_fee IS NULL THEN 1 END) AS withoutLabfee
FROM course_relation