从mySQL查询中删除列

时间:2018-09-10 20:16:24

标签: mysql

我对数据库中的重力形式表进行以下查询。我需要为cyfe仪表板格式化结果。这意味着我需要删除uid列。虽然我似乎无法正确解决问题

SELECT entry_id as uid
,(SELECT meta_value from wp_gf_entry_meta where meta_key=1.3 and entry_id = uid) as 'NAME'
,(SELECT meta_value from wp_gf_entry_meta where meta_key=3 and entry_id = uid) as 'PHONE'
FROM wp_gf_entry_meta
GROUP BY uid ORDER BY uid

当前结果(摘要数据)

enter image description here

需要的结果(虚拟数据)

enter image description here

尝试过:

SELECT *
,(SELECT meta_value from wp_gf_entry_meta where meta_key=1.3 and entry_id = uid) as 'NAME'
,(SELECT meta_value from wp_gf_entry_meta where meta_key=3 and entry_id = uid) as 'PHONE'
FROM wp_gf_entry_meta
GROUP BY uid ORDER BY uid

错误:“ where子句”中的未知列“ uid”

我也尝试过这个:

SELECT *
,(SELECT meta_value from wp_gf_entry_meta where meta_key=1.3) as 'NAME'
,(SELECT meta_value from wp_gf_entry_meta where meta_key=3) as 'PHONE'
FROM wp_gf_entry_meta

错误:子查询返回多于1行

也尝试过:

SELECT
,(SELECT meta_value from wp_gf_entry_meta where meta_key=1.3 and entry_id = uid) as 'NAME'
,(SELECT meta_value from wp_gf_entry_meta where meta_key=3 and entry_id = uid) as 'PHONE'
FROM wp_gf_entry_meta
GROUP BY entry_id

错误:查询(1064)中的错误:第2行'((从wp_gf_entry_meta中选择meta_value,其中meta_key = 1.3并且entry_id = uid)'附近的语法错误

2 个答案:

答案 0 :(得分:1)

与其依赖别名和黑魔法的相关子查询,不如将其切换为LEFT OUTER JOIN:

SELECT meta2.meta_value as 'NAME', meta3.meta_value as 'PHONE'
FROM wp_gf_entry_meta meta1
    LEFT OUTER JOIN  wp_gf_entry_meta meta2
        ON meta1.entry_id = meta2.entry_id 
    LEFT OUTER JOIN wp_gf_entry_meta meta3
        ON meta1.entry_id = meta3.entry_id
GROUP BY meta1.entry_id /*uid*/

现在可以清楚地知道发生了什么,删除一列并不意味着失去那些相关子查询正常工作所必需的别名。

如果您想坚持使用相关子查询方法,则需要对FROM子句中的表进行别名化以用于子查询(因为我们丢失了uid的别名): / p>

SELECT
   (SELECT meta_value from wp_gf_entry_meta where meta_key=1.3 and entry_id = meta_uid.entry_id) as 'NAME',
   (SELECT meta_value from wp_gf_entry_meta where meta_key=3 and entry_id = meta_uid.entry_id) as 'PHONE'
FROM wp_gf_entry_meta AS meta_uid
GROUP BY entry_id

如果这仍然在子查询中抱怨多个结果,则切换到允许多个结果通过的LEFT OUTER JOIN。然后,您可以了解为什么它会在SQL中进行乘法和更正,而不是被相关子查询蒙住眼睛。

答案 1 :(得分:0)

您可以尝试删除第一个SELECT entry_id as uid并改为使用WITH。

WITH entry_id as uid
    (SELECT meta_value from wp_gf_entry_meta where meta_key=1.3 and entry_id = uid) as 'NAME'
    ,(SELECT meta_value from wp_gf_entry_meta where meta_key=3 and entry_id = uid) as 'PHONE'
    FROM wp_gf_entry_meta
    GROUP BY uid ORDER BY uid