我试图让它成为一种在同一查询中进行选择的方法。我正在研究wordpress数据库,我有这些SQL查询可以自己运行:
SELECT `meta_value` AS 'Name' FROM `wp_postmeta` WHERE `meta_key` = "myfield1" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Department' FROM `wp_postmeta` WHERE `meta_key` = "myfield2" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Location' FROM `wp_postmeta` WHERE `meta_key` = "myfield3" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Job Title' FROM `wp_postmeta` WHERE `meta_key` = "myfield4" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Social Number' FROM `wp_postmeta` WHERE `meta_key` = "myfield5" ORDER BY `post_id` ASC
但我希望将它们全部放在同一个查询中,以便稍后我可以在报告中导出数据。这是我尝试过的:
SELECT
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield1" ORDER BY `post_id` ASC) As name,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield2" ORDER BY `post_id` ASC) AS department,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield3" ORDER BY `post_id` ASC) AS location,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield4" ORDER BY `post_id` ASC) AS jobtitle,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield5" ORDER BY `post_id` ASC) AS socnumber
但是那些返回的命令不同步。任何人都知道如何解决这个问题?
#2014 - Commands out of sync; you can't run this command now
编辑: 我正在查询wp_postmeta表,它有4列meta_id,post_id,meta_key和meta_value列。我从我添加的自定义字段中选择了meta_value(称为myfield1,保存在meta_key列中)。我通过post_id订购,这是wordpress中帖子的ID,所以我按时间顺序排序。
但我有5个自定义字段,myfield1到myfield5。我想一次查询所有这些。
答案 0 :(得分:1)
一种方法是使用条件聚合:
SELECT MAX(CASE WHEN `meta_key` = 'myfield1' THEN meta_value END) as Name,
MAX(CASE WHEN `meta_key` = 'myfield2' THEN meta_value END) as Department,
MAX(CASE WHEN `meta_key` = 'myfield3' THEN meta_value END) as Location,
MAX(CASE WHEN `meta_key` = 'myfield4' THEN meta_value END) as JobTitle,
MAX(CASE WHEN `meta_key` = 'myfield5' THEN meta_value END) as SocialNumber
FROM `wp_postmeta`
WHERE `meta_key` = "myfield5"
GROPU BY post_id
ORDER B post_id ASC;
答案 1 :(得分:0)
您无法使用不同的别名(“' meta_value' AS'名称' ...等)选择相同的列,并将结果作为一个集合。该列只能有一个名称!
你能做的最好的事情就是这样:
SELECT `meta_value`, `meta_key`
FROM `wp_postmeta`
WHERE `meta_key` IN ("myfield1", "myfield2", "myfield3", "myfield4", "myfield5")
ORDER BY `post_id` ASC
这将在一个结果集中为您提供所有值,并使用meta_key
列,以便您可以分辨哪个。
答案 2 :(得分:0)
要获得一个包含五列的结果集(每个自定义字段一个),您必须将表连接到自己五次......
这样的事情:
SELECT
pm1.meta_value AS 'Name'
pm2.meta_value AS 'Department'
pm3.meta_value AS 'Location'
pm4.meta_value AS 'Job Title'
pm5.meta_value AS 'Social Number'
FROM `wp_postmeta` pm1
JOIN `wp_postmeta` pm2 ON pm1.post_id = pm2.post_id
JOIN `wp_postmeta` pm3 ON pm1.post_id = pm3.post_id
JOIN `wp_postmeta` pm4 ON pm1.post_id = pm4.post_id
JOIN `wp_postmeta` pm5 ON pm1.post_id = pm5.post_id
WHERE
pm1.meta_key = "myfield1"
AND pm2.meta_key = "myfield2"
AND pm3.meta_key = "myfield3"
AND pm4.meta_key = "myfield4"
AND pm5.meta_key = "myfield5"
ORDER BY `post_id` ASC
我还没有检查过SQL语法,所以请原谅我是否存在语法错误!
假设这是mySQL?