简体   繁体   中英

Query Two Tables - but not trying to JOIN?

I have two tables that almost have identical columns. The first table contains the "current" state of a particular record and the second table contains all the previous stats of that records (it's a history table). The second table has a FK to the first table.

I'd like to query both tables so I get the entire records history, including its current state in one result. I don't think a JOIN is what I'm trying to do as that "joins" multiple tables "horizontally" (one or more columns of one table combined with one or more columns of another table to produce a result that includes columns from both tables). Rather, I'm trying to "join"(???) the tables "vertically" (meaning, no columns are getting added to the result, just that the results from both tables are falling under the same columns in the result set).

Not exactly sure if what I'm expressing make sense -- or if it's possible in MySQL.

UNION.

Select colA, colB From TblA

UNION

Select colA, colB From TblB

To accomplish this, you could use a UNION between two SELECT statements. I would also suggest selecting from a derived table in the following manner so that you can sort by columns in your result set. Suppose we wanted to combine results from the following two queries:

SELECT FieldA, FieldB FROM table1;
SELECT FieldX, FieldY FROM table2;

We could join these with a UNION statement as follows:

SELECT Field1, Field2 FROM (
    SELECT FieldA AS `Field1`, FieldB AS `Field2` FROM table1 
    UNION SELECT FieldX AS `Field1`, FieldY AS `Field2` FROM table2) 
AS `derived_table` 
ORDER BY Field1 ASC, Field2 DESC

In this example, I have selected from table1 and table2 fields which are similar, but not identically named, sharing the same data type. They are matched up using aliases ( eg , FieldA in table1 and FieldX in table2 both map to Field1 in the result set, etc. ).

If each table has the same column names, field aliasing is not required, and the query becomes simpler.


Note: In MySQL it is necessary to name derived tables, even if the name given is not intended to be used.

Your after a left join on the first table. That will make the right side I'd he their a number (exists in both) or null (exists only in the left table )

You want

select lhs.* , rhs.id from lhs left join  rhs using(Id) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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