将查询结果作为单行获取?

时间:2016-02-15 09:35:33

标签: mysql

这是我得到的结果表:

id | reference_field | value | ------------------------------------------------------
4 | product_name | name of the product |
4 | product_description | description of the product|
...

我正在使用以下查询:

SELECT 
 CASE 
WHEN reference_field = "product_name" THEN value 
END AS product_name, 
CASE 
 WHEN reference_field = "product_description" THEN value 
END AS product_description 
FROM my_table 
WHERE id=4`

我最终得到:
product_name | product_description | -------------------------------------------------
name of the product | NULL |
NULL | description of the product|

但我想得到的是:
product_name | product_description | -------------------------------------------------
name of the product | description of the product|

是否有可能,我应该在查询中修改什么?

由于

2 个答案:

答案 0 :(得分:3)

您可以使用联接:

for folder in directory_tree["ControlPatch_CPR"]: //Loop for checking dict entries
    for subfolder in folder:
        print str(folder) + " --- " + str(subfolder)
for folder in directory_tree["ControlPatch_CPR"]:
    for subfolder in folder:
        if len(subfolder) == 1:
            subfolder = "0" + subfolder
        ftp.cwd("/")
        print "\nretrieving {0}/ControlPatch/{1}/{2}/whatsnew.txt ...".format(ftplocation, folder, subfolder)
        with open("{0}.{1}.whatsnew.txt".format(folder, subfolder), "wb") as whatsnew:
            ftp.cwd("/ControlPatch/{0}/{1}".format(folder, subfolder))
            print "working directory: " + ftp.pwd()
            ftp.retrbinary("RETR /ControlPatch/{0}/{1}/whatsnew.txt".format(folder, subfolder), whatsnew.write)

如果您没有要包含在查询中的许多字段,则此方法效果最佳,因为您必须在查询中为要添加的每个列添加另一个表。但它的优势在于您可以显示任意数量的产品,而不仅仅是一种产品。

答案 1 :(得分:1)

您可以使用MAX:

SELECT 
      max(CASE 
          WHEN reference_field = "product_name" THEN value 
          END) AS product_name, 
      max(CASE 
          WHEN reference_field = "product_description" THEN value 
          END) AS product_description 
FROM my_table 
WHERE id=4`