MySql根据同一个表中的值从表中选择某些列

时间:2014-06-02 04:44:17

标签: mysql

在MySql中,如何根据我选择的某列的值来选择某些列?

"id"    "postTitle" "postBody"  "postCategory"  "postStatus"    "userId"    "userName"
"1"     "Title 1"   "Body 1"    "Alcohol"       "0"             "1"         "norman"
"2"     "Title 2"   "Body 2"    "Books"         "1"             "1"         "norman"

例如:从上表中,我尝试仅选择postTitle postStatus = 0postTitle& postBody&如果postCategory

,则postStatus != 0

它可以解决这个问题,但这不会起作用

select if postStatus != 0 then
postTitle, postBody, postCategory
else
postTitle
End If
from tablea where id = 2;

我尝试使用大小写,但它适用于一列而不是我选择更多

select case postStatus when 1 then
postTitle, postBody
else
postTitle
End
from tablea where id = 2;

有没有办法像我尝试做的那样?

2 个答案:

答案 0 :(得分:0)

尝试使用UNION运算符

SELECT postTitle ,'' AS postBody ,'' AS  postCategory FROM tableName 
WHERE postStatus = '0'
UNION 
SELECT postTitle ,postBody , postCategory FROM tableName
WHERE postStatus != '0'

答案 1 :(得分:0)

  

我尝试仅选择postTitle postStatus = 0postTitle& postBody&如果postCategory

,则postStatus != 0

您必须使用case检查每个要显示的列。

示例

select 
  , posttitle
  , case when poststatus = 0 then '' else postbody end as postbody
  , case when poststatus = 0 then '' else postCategory end as postCategory
from tableA where id=2;