在我的数据库中,我必须使用一对多(可选)关系表1....0,*
Table1:
+--+---------+
|id| name |
+--+---------+
| 1| user1 |
| 2| user2 |
| 3| user3 |
+--+---------+
Table2
+--+------+-------+
|id|tb1_ID|city |
+--+------+-------+
| 1| 1 | a |
| 2| 1 | b |
| 3| 2 | c |
+--+------+-------+
现在我想要表2中的所有当前记录和table2的前1个元素(对于每个表1行)
像
+----+------+----+--------+---------+
|p.id|p.name|c.id|c.tb1_ID|c.city |
+----+------+----+--------+---------+
| 1 | user1| 1 | 1 | a |
| 2 | user2| 3 | 2 | c |
| 3 | user3|null| null | null |
+----+------+----+--------+---------+
如何???
答案 0 :(得分:2)
例如,使用此WITH common_table_expression
和ROW_NUMBER
函数:
WITH cte AS(
SELECT t1.id AS t1ID
, t1.name
, t2.id AS t2ID
, t2.tb1_ID
, t2.city
, ROW_NUMBER()OVER(Partition By t1.id Order By t2.id)AS t1RowNum
FROM Table1 t1 LEFT OUTER JOIN Table2 t2 ON t1.id=t2.tb1_ID
)
SELECT cte.*
FROM cte
WHERE t1RowNum = 1
答案 1 :(得分:1)
您必须使用带有OUTER APPLY的子查询来隔离右表中的单行。
select t1.*, t2.*
from table1 t1
outer apply
(
select top 1 *
from table2
where tb1_id = t1.id
order by id
) as t2
答案 2 :(得分:-1)
假设您有1对多的关系,您想使用LEFT OUTER JOIN
:
SELECT p.id, p.name, c.id, c.tb1_ID, c.city
FROM Table1 p
LEFT OUTER JOIN Table2 c
ON p.id = c.tb1_ID
如果你有多对多,你需要决定如何限制表2。