dongzhanyan3667 2012-03-09 00:37
浏览 264
已采纳

从两个不同的表中选择两列,每个表具有不同的列名

I'm having trouble figuring out this query. I'm using PHP and postgresql 9.1. I want to be able to select fields from rows based on a criteria in another field like so.

Table A has columns:

vid, title, description, col4, col5, col6, col7

Table B has columns:

pid, title, description, colx, coly

I want to search title and description from both tables and if a match is found, return the vid or pid of the row it was found in.

What I've tried so far:

SELECT vid FROM tableA WHERE title LIKE %somevalue%
UNION
SELECT pid FROM tableB WHERE title LIKE %somevalue%

Problem is when I do that and it finds a match for tableB which returns the correct value but assigned to vid column in the array. The php array displays

Array ( [0] => Array ( [vid] => 100007 ) )

When it should be

Array ( [0] => Array ( [pid] => 100007 ) )

It doesn't give me the correct column name for the table. It only gives me the column name of the first select statement.
Also, it only returns one or the other. If the value is found in both I want both values with both columns.

  • 写回答

4条回答 默认 最新

  • doudi1978 2012-03-09 02:17
    关注
    SELECT
      a.vid,
      b.pid
    FROM (
      SELECT vid, ROW_NUMBER() OVER (ORDER BY vid) AS rn
      FROM tableA
      WHERE title LIKE '%somevalue%'
    ) a
    FULL JOIN (
      SELECT pid, ROW_NUMBER() OVER (ORDER BY pid) AS rn
      FROM tableB
      WHERE title LIKE '%somevalue%'
    ) b
    ON a.rn = b.rn
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决