Postgresql:如何连接同一个表的多个选择

时间:2018-04-06 21:13:14

标签: sql postgresql

如何在PostgreSQL中完成以下查询?

SELECT "ItemNumber" AS "Value", 'ItemNumber' AS "Field" FROM item.items JOIN
SELECT "ItemName" AS "Value", 'ItemName' AS "Field" FROM item.items JOIN
SELECT "ItemBarcode" AS "Value", 'ItemBarcode' AS "Field" FROM item.items;

结果应采用以下格式:

items: [
{
"Value": "12345677",
"Field": "ItemNumber" 
}, {
"Value": "98776",
"Field": "ItemNumber" 
}, {
"Value": "test77 1",
"Field": "ItemName" 
}, {
"Value": "test77 2",
"Field": "ItemName" 
}, {
"Value": "test77 3",
"Field": "ItemName" 
}, {
"Value": "2342349872934877293847",
"Field": "ItemBarcode" 
}, {
"Value": "9872349877239487923847",
"Field": "ItemBarcode" 
}]

或者有没有更好的方法通过SQL获得结果?

1 个答案:

答案 0 :(得分:0)

您在寻找union all吗?

SELECT "ItemNumber" AS "Value", 'ItemNumber' AS "Field" FROM item.items 
UNION ALL
SELECT "ItemName" AS "Value", 'ItemName' AS "Field" FROM item.items 
UNION ALL
SELECT "ItemBarcode" AS "Value", 'ItemBarcode' AS "Field" FROM item.items;