MySQL单查询多个结果

时间:2017-04-20 02:24:03

标签: php mysql

我正试图通过以下查询获取我想要的所有信息。这是评论值,其中status = 0和SUM指向status = 0status = 1的位置。这是我到目前为止所得到的(此时我无法获取评论值)

SELECT
  IF(status = 0, comment, NULL) AS com,
  SUM(IF(status = 0, points, 0)) AS points1,
  SUM(IF(status = 1, points, 0)) AS points2
FROM `tablename`
  WHERE mid = $mid
  AND stage = 0 

表格数据:

+----+--------+--------+-----------+-----+------+
| id |   mid  | points |  comment  |stage|status|
+----+--------+--------+-----------+-----+------+
|  1 | 500    |   15   | Text here |  0  |   0  |
|  2 | 500    |   5    | Blablabla |  0  |   1  |
|  3 | 20     |   7    |           |  1  |   0  |
|  4 | 356    |   10   | More text |  0  |   2  |
|  5 | 9      |   0    |           |  1  |   0  |
|  6 | 52     |   5    | Text etc  |  0  |   1  |
|  7 | 520    |   13   | Texting   |  1  |   0  |
|  8 | 540    |   8    |           |  0  |   0  |
+----------------------------------------+------+

结果我正在寻找:

  • mid = 500stage = 0
  • 的位置
  • 如果status = 0获得积分(在这种情况下为15
  • 如果status = 1获得积分(在这种情况下为5
  • 如果status = 0给我发表评论(本例中为Text here

1 个答案:

答案 0 :(得分:1)

如果使用聚合函数,则应聚合所有列。我更喜欢CASEIF(),因为前者是标准SQL:

SELECT GROUP_CONCAT(CASE WHEN status = 0 THEN comment END) AS com,
       SUM(CASE WHEN status = 0 THEN points ELSE 0 END) AS points_0,
       SUM(CASE WHEN status = 1 THEN points ELSE 0 END) AS points_1
FROM `tablename`
WHERE mid = $mid AND stage = 0 ;

评论:

  • 如果多个行与条件匹配且GROUP_CONCAT()status = 0,则会使用msg = MIMEMultipart() msg['From'] = "" msg['Subject'] = "" part = MIMEApplication(open(attachment_path, 'rb').read()) filetype = os.path.splitext(attachment_path)[-1][1:] newfilename = 'resume' + '.' + filetype if filetype=="pdf": part["Content-Type"] ="application/pdf" elif filetype=="doc" or filetype=="docx": part['Content-Type']="application/msword" else: pass part.add_header('Content-Disposition', 'attachment', filename=newfilename) msg.attach(part)
  • "点"的名称列匹配要比较的状态。