简体   繁体   中英

Sqlite - query 1 column in two identical tables where column equals a value

I have two identical tables (month1, month2) and I am trying to find all records from both tables where task1_done = 1. I want the last row in that set (i move cursor to last for this). I have played with inner outer natural joins but can't seem to get month2 values. Here is what I have:

String query = "SELECT m1.columnA, m1.columnB, m1.columnC, m1.columnD, m1.columnE, m1.columnF FROM month1 m1, month2 m2 WHERE m1.task1_done = 1 OR m2.task1_done = 1";

Any help would be great!

I think you want a union all for this query:

select m.*
from (select *
      from months1
      union all
      select *
      from months2
     ) m
where task1_done = 1;

Note: I have used * as a convenience because you said the two tables have the same structure. You should actually list the columns that you want from the two tables.

In general, having two tables with the same layout is a sign of a bad database design. It is usually better to have a bigger table, with another column identifying "month1" or "month2".

EDIT:

SQL tables do not have a "last" value. If you have a an id or timestamp column that you can use for ordering, then you can do:

select m.*
from (select *
      from months1
      union all
      select *
      from months2
     ) m
where task1_done = 1
order by id desc
limit 1;

Are these tables related or have any references? if not you can have separate statement and do a union

ie

select top 1 column1, column2.. from month1 WHERE task1_done = 1 order by IdentityColumn Desc
union 
select top 1 column1, column2.. from month2 WHERE task1_done = 1 order by IdentityColumn Desc

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