简体   繁体   English

PostgreSQL-将2个不同表中的2个SELECT语句分成2列?

[英]PostgreSQL - 2 SELECT Statements from 2 different tables into 2 Columns?

I asked a similar question yesterday but still having a slight problem on output. 昨天我问了类似的问题,但输出仍然有一点问题。 Unions only always combines it into one column and there is no relation to do a join. 联合仅将其始终合并为一列,并且没有关系进行联接。 Here is what I want. 这就是我想要的。 I don't want to combine. 我不想合并。

SELECT prd_id FROM products WHERE title LIKE %$var%;

AND

SELECT lst_id FROM lists WHERE title LIKE %$var%;

I want both of these in one query and output the results it finds into 2 columns IF there is a result for either one. 我希望在一个查询中将这两个都输出,如果找到任一结果,则将其找到的结果输出到2列中。 I also would like to use a LIMIT at the end too. 我也想在末尾使用LIMIT。

So for example if both tables have an item that matches the title then it will return something like. 因此,例如,如果两个表都具有与标题匹配的项目,则它将返回类似内容。 Note the values will be whatever it matched in each table. 注意,这些值将是每个表中匹配的值。 The point is just to be in 2 columns instead of one like Unions output. 关键是要放在2列中,而不是像Unions这样的输出中。

+-----------------+  
| prd_id | lst_id |   
+-----------------+   
|  value | value  |   
+-----------------+   

I get close but just can't it exactly. 我接近了,但不能完全一样。

To make it clear, the PHP print_r output should be like this. 为了清楚起见,PHP print_r输出应如下所示。 This example is if 2 items are matched in the list table only 此示例是仅在列表中匹配2个项目的情况

Array ( [0] => Array ( [lst_id] => 100007 ) [1] => Array ( [lst_id] => 100008 ))

This example is if 1 item from each table is matched 此示例是每个表中是否有一项匹配

Array ( [0] => Array ( [prd_id] => 100006 ) [1] => Array ( [lst_id] => 100008 ))

There can be any number of matches from either of the tables. 任何一个表中都可以有任意多个匹配项。

The simplest answer would be to union the results into different column, like so: 最简单的答案是将结果合并到不同的列中,如下所示:

SELECT prd_id, 0 lst_id FROM products WHERE title LIKE %$var%
UNION ALL
SELECT 0 prd_id, lst_id FROM lists WHERE title LIKE %$var%;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM