问题
I want to join 3 tables which Table A have date and time in different field that need to be combined first so it can be compared on Table B using field timestamp.
Table A
userid | date_in | check_in
--------+------------+----------
145 | 2017-01-23 | 08:56:05
254 | 2017-01-24 | 08:56:54
202 | 2017-01-25 | 08:53:26
15 | 2017-01-26 | 08:47:40
Table B
userid | checktime | sn
--------+---------------------+---------------
145 | 2017-01-23 08:56:05 | 0345135200184
254 | 2017-01-24 08:56:54 | 0345135200184
202 | 2017-01-25 08:53:26 | 0345135200184
15 | 2017-01-26 08:47:40 | 0345135200184
Table 3
sn | alias
---------------+-------------
0345135200184 | Alam Sutera
I tried this:
select process.userid, process.date_in, process.check_in, checkinout.checktime, iclock.alias from process
inner join checkinout on checkinout.checktime=(select cast (date_in as timestamp(0)) + (check_in - time '00:00:00') checktime from process)
inner join iclock on checkinout.sn=iclock.sn
order by userid desc limit 10;
I also tried this:
select checkinout.userid, checkinout.checktime, checkinout.sn from checkinout
inner join lateral
(select distinct userid, date_in, check_in from process where
date_in=(select checktime::date from checkinout) and
check_in=(select checktime::time from checkinout)
order by date_in asc limit 1)
process ON true;
Both of them give error: ERROR: more than one row returned by a subquery used as an expression
Expected Result:
userid | date_in | check_in | checktime | alias
--------+------------+----------+--------------------+-------
145 | 2017-01-23 | 08:56:05 | 2017-01-21 09:49:04|Alam Sutera
254 | 2017-01-24 | 08:56:54 | 2017-01-21 07:57:05|Alam Sutera
202 | 2017-01-25 | 08:53:26 | 2017-01-21 14:27:00|Alam Sutera
15 | 2017-01-26 | 08:47:40 | 2017-01-21 06:30:34|Alam Sutera
Can someone help me to solve this? Thank you for the help.
回答1:
By adding date
and time
field you will get the timestamp which you can compare for join. so you can write your query like below:
select
t1.userid, t1.date_in, t1.check_in, t2.checktime, t3.alias
from process t1
inner join checkinout t2 on t2. checktime= date_in + check_in and t1.userid=t2.userid
inner join table3 t3 on t2.sn=t3.sn
DEMO
Regarding you error you have mentioned in your question ERROR: more than one row returned by a subquery used as an expression
is due to join condition you have used.
回答2:
You can convert your separate Date and Time columns to a Timestamp using the To_Timestamp function as shown below. This should enable you to join TableA and TableB as desired.
select * from tableA a
join tableB b
on a.userid = b.userid
and to_timestamp(a.date_in || ' ' || a.check_in, 'YYYY-MM-DD HH24:MI:SS') = b.checktime
As demonstrated here
来源:https://stackoverflow.com/questions/64314541/join-multiple-table-based-on-timestamp-and-another-condition