过滤表union mysql中的行

时间:2016-09-06 04:03:18

标签: mysql sql union

你好我在这个糟糕的数据库结构中遇到了很多困难,我需要帮助过滤表联合中的行是否可能?

我正在尝试在表格中选择pre1, pre2, pre3, pre4, pre5,其中值不为空,因此所有行都会显示,但是当我尝试过滤掉{{1}的行时我收到错误,因为我不知道该怎么做。你能救我吗?

我正在处理的代码就是这个

trno = <value>

我也试过这个

SELECT * FROM
(
SELECT pre1 AS col FROM ccsubject
UNION
SELECT pre2 AS col FROM ccsubject
UNION
SELECT pre3 AS col FROM ccsubject
UNION
SELECT pre4 As col FROM ccsubject
UNION
SELECT pre5 AS col FROM ccsubject
) T1
WHERE col IS NOT NULL

这是我的表结构

enter image description here

3 个答案:

答案 0 :(得分:0)

您还需要选择tr字段。

SELECT * FROM
(
    SELECT pre1 AS col, trno AS tr FROM ccsubject
    UNION
    SELECT pre2 AS col, trno AS tr FROM ccsubject
    UNION
    SELECT pre3 AS col, trno AS tr FROM ccsubject
    UNION
    SELECT pre4 As col, trno AS tr FROM ccsubject
    UNION
    SELECT pre5 AS col, trno AS tr FROM ccsubject
) t
WHERE t.col IS NOT NULL AND
      t.tr = 29005

答案 1 :(得分:0)

  • 如果您只想要pre1,pre2,pre3,pre4,pre5,我不确定为什么要使用select *。
  • 另外,为什么您希望所有名为col
  • 的预列

SELECT pre1, pre2, pre3, pre4, pre5 FROM ccsubject where col is not NULL

答案 2 :(得分:0)

试试这个:

SELECT * FROM
(
SELECT pre1 AS col FROM ccsubject WHERE trno = 29005 AND pre1 IS NOT NULL
UNION
SELECT pre2 AS col FROM ccsubject WHERE trno = 29005 AND pre2 IS NOT NULL
UNION
SELECT pre3 AS col FROM ccsubject WHERE trno = 29005 AND pre3 IS NOT NULL
UNION
SELECT pre4 As col FROM ccsubject WHERE trno = 29005 AND pre4 IS NOT NULL
UNION
SELECT pre5 AS col FROM ccsubject WHERE trno = 29005 AND pre5 IS NOT NULL
) T1