开发者

Finding a record in one of 2 tables

In PostgreSQL 8.4.8 database I have 2 tables: noreset and track.

They have exactly same column names and contain records identified by unique id.

A record can be present only in one of the tables, for example:

# select qdatetime, id, beta_prog, emailid, formfactor 
    from noreset where id='20110922124020305';
      qdatetime      |        id         | beta_prog |     em开发者_运维百科ailid      | formfactor
---------------------+-------------------+-----------+------------------+------------
 2011-09-22 11:39:24 | 20110922124020305 | unknown   | 4bfa32689adf8189 | 21
(1 row)

# select qdatetime, id, beta_prog, emailid, formfactor
    from track where id='20110922124020305';
 qdatetime | id | beta_prog | emailid | formfactor
-----------+----+-----------+---------+------------
(0 rows)

I'm trying to come up with a join statement, which would find a record by id in one of the both tables. The background is that I have a PHP-script, which was always using 1 table, but now suddenly I'm requested to search in both tables.

Can this be done? Is it a full outer join? I'm confused how to specify the column names in my SQL query (i.e. I must prepend a table id, but which one?)...


You should use union:

select qdatetime, id, beta_prog, emailid, formfactor, 'noreset' as tableOrigin
    from noreset where id='20110922124020305'
union
select qdatetime, id, beta_prog, emailid, formfactor, 'track' as tableOrigin
    from track where id='20110922124020305'

(union remove duplicate lines, if you want all use union all)

If you are goint to use this very often is better to make a view:

CREATE VIEW yourviewname as 
select qdatetime, id, beta_prog, emailid, formfactor, 'noreset' as tableOrigin
    from noreset
union
select qdatetime, id, beta_prog, emailid, formfactor, 'track' as tableOrigin
    from track

and then your query would be:

SELECT qdatetime, id, beta_prog, emailid, formfactor
  FROM yourviewname
 WHERE id='20110922124020305'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜