简体   繁体   English

SQL JOIN有条件地包含多行

[英]SQL JOIN with multiple rows conditionally

I have 2 tables in a SQLite database that I am accessing it via PHP 我通过PHP访问SQLite数据库中有2个表
This is sample data, it is enough to describe what I want to do but not why. 这是示例数据,足以描述我想做的事情,而不是为什么。
Lets call these tables: TableA , TableB , and TableC 我们称这些表为: TableATableBTableC

------------------------
|  Unique_ID  |  Name  |
------------------------
|  1          | Sam    |
------------------------
|  2          | Bob    |
------------------------
|  3          | Jill   |
------------------------

*Assume more rows for other possible foreign keys below
--------------------------------------------
|  Unique_ID  |  Foreign_Key  | Time_Stamp |
--------------------------------------------
|  1          | 1             | 1495298339 |
--------------------------------------------
|  2          | 1             | 1495298350 |
--------------------------------------------
|  3          | 1             | 1495298365 |
--------------------------------------------

What I want in my output would be something line this 我想要的输出是这样的

------------------------------------
|  Name  | First_Time |  Last_Time |
------------------------------------
|  Sam   | 1495298339 | 1495298365 |
------------------------------------
|  Jill  | 1495298787 | 1495298805 |
------------------------------------

Basically I want to pull the fist and last time stamp into the 1st table, but I am not sure how to do a join line this or if it is even possible, multi-layered select queries with limited results of 1? 基本上,我想将第一个和最后一个时间戳记放入第一个表中,但是我不确定该如何执行联接行,或者即使有可能,也要对结果有限的1进行多层选择查询?

I am hoping there is a way to avoid looping through each value in TableA and making two separate queries to get the first (lowest) and last (highest) Time_Stamp in TableB 我希望有一种方法可以避免遍历TableA每个值,并进行两个单独的查询以获取TableB的第一个(最低)和最后一个(最高) Time_Stamp

You can do a join between the first table and a processed version of the second table. 您可以在第一个表和第二个表的已处理版本之间进行联接。 The second table is a group by using the Foreign_Key , and the computed values are the minimum and maximum of Time_Stamp . 第二个表是使用Foreign_Key的组,计算出的值是Time_Stamp的最小值和最大值。 Something like this: 像这样:

select A.Unique_Id, B.First_Time, B.Last_Time
from TableA as A
join (
    select Foreign_Key, min(Time_Stamp) as First_Time, max(Time_Stamp) as Last_Time
    from Table B
    group by Foreign_Key
) as B
on A.Unique_Id = B.Foreign_Key
SELECT table1.Name, MIN( table2 .Time_Stamp ) AS firstTime, MAX( table2 .Time_Stamp ) AS lastTime
FROM  `table1` 
LEFT OUTER JOIN table2 ON table1.Unique_Id = table2.Unique_Id
GROUP BY table1.Unique_Id

Hope this will help you. 希望这会帮助你。

SELECT TableA.name, MIN(TableB.timeid), MAX(TableB.timeid) FROM TableA

INNER JOIN TableB ON TableA.id = TableB.TableA_id 

GROUP BY TableB.TableA_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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