postgresql PostgreSQL单查询SELECT单行FROM没有JOIN的两个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27323922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PostgreSQL single query SELECT single row FROM two tables without JOIN
提问by Joe Love
The result of a query I need to create will only return a single row. The data I need to pull comes from two tables without any relational columns. The second table only has additional rows added once per year so I'll construct the query via PHP as necessary.
我需要创建的查询结果只会返回一行。我需要提取的数据来自两个没有任何关系列的表。第二个表每年只添加一次额外的行,因此我将根据需要通过 PHP 构建查询。
I know how to use SQL sub-SELECTs however I'm notsure how to SELECT
multiple columns FROM
a second table when there is no relational data in a performance oriented/dynamic way.
我知道如何使用SQL子选择但是我不知道如何SELECT
多列FROM
第二表时,有在以业绩为导向/动态的方式没有任何关系数据。
Here is a static example where I use multiple sub-SELECTs to visualize what I'm trying to do...
这是一个静态示例,我使用多个子选择来可视化我正在尝试做的事情......
SELECT t1.a,
t1.b,
t1.c,
(SELECT t2.d FROM table2) AS d,
(SELECT t2.e FROM table2) AS e,
(SELECT t2.f FROM table2) AS f,
(SELECT t2.g FROM table2) AS g,
t1.h,
t1.i
FROM table1 AS t1;
How do I dynamically and efficiently pull multiple columns from a second table that has no relational columns with the first table?
如何从与第一个表没有关系列的第二个表中动态有效地提取多个列?
I do not want to create a second separate query as it would be cheap solution, most likely have someimpact on performance and worst of all I wouldn't expand my understanding of SQL.
我不想创建第二个单独的查询,因为它是廉价的解决方案,很可能会对性能产生一些影响,最糟糕的是我不会扩展我对 SQL 的理解。
回答by Joe Love
Sounds like you need a cartesian join (no join) -- but you WILL multiply the values together (ie, if table 1 has 100 rows and table 2 has 10 rows, you'll return 1000 rows)
听起来你需要一个笛卡尔连接(无连接)——但你会将这些值相乘(即,如果表 1 有 100 行,表 2 有 10 行,你将返回 1000 行)
SELECT t1.a,
t1.b,
t1.c,
t2.d,
t2.e,
t2.f,
t2.g,
t1.h,
t1.i
FROM table1 AS t1, table2 as t2;
回答by Denis de Bernardy
The syntax to do so is:
这样做的语法是:
SELECT t1.a,
t1.b,
t1.c,
t2.d,
t2.e,
t2.f,
t2.g,
t1.h,
t1.i
FROM table1 AS t1, table2 as t2;
If you're not joining the two tables though, you'll usually want two queries. Else, you'll get a cartesian product of the two tables:
但是,如果您不连接这两个表,则通常需要两个查询。否则,您将获得两个表的笛卡尔积: