回答編集履歴
2
追記
test
CHANGED
@@ -44,8 +44,6 @@
|
|
44
44
|
|
45
45
|
最終的にkubunが不要なら、相関副問い合わせでdept_idを求めておけば、user_rel_table との結合は不要になります。
|
46
46
|
|
47
|
-
|
48
|
-
|
49
47
|
```SQL
|
50
48
|
|
51
49
|
select
|
@@ -77,3 +75,39 @@
|
|
77
75
|
on d.id=uv.dept_id
|
78
76
|
|
79
77
|
```
|
78
|
+
|
79
|
+
相関副問い合わせを、where条件で使用する方法もあります。
|
80
|
+
|
81
|
+
```SQL
|
82
|
+
|
83
|
+
SELECT
|
84
|
+
|
85
|
+
u.id,
|
86
|
+
|
87
|
+
u.user_name,
|
88
|
+
|
89
|
+
ur.user_id,
|
90
|
+
|
91
|
+
ur.dept_id,
|
92
|
+
|
93
|
+
ur.kubun,
|
94
|
+
|
95
|
+
d.dept_name,
|
96
|
+
|
97
|
+
d.dept_address
|
98
|
+
|
99
|
+
FROM users_table u
|
100
|
+
|
101
|
+
LEFT JOIN user_rel_table ur
|
102
|
+
|
103
|
+
ON u.id = ur.user_id
|
104
|
+
|
105
|
+
LEFT JOIN dept_table d
|
106
|
+
|
107
|
+
ON d.id = ur.dept_id
|
108
|
+
|
109
|
+
where ur.kubun is null
|
110
|
+
|
111
|
+
or ur.kubun=(select min(kubun) from user_rel_table where user_id=u.id)
|
112
|
+
|
113
|
+
```
|
1
追記
test
CHANGED
@@ -43,3 +43,37 @@
|
|
43
43
|
```
|
44
44
|
|
45
45
|
最終的にkubunが不要なら、相関副問い合わせでdept_idを求めておけば、user_rel_table との結合は不要になります。
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
```SQL
|
50
|
+
|
51
|
+
select
|
52
|
+
|
53
|
+
uv.id,
|
54
|
+
|
55
|
+
uv.user_name,
|
56
|
+
|
57
|
+
d.dept_id,
|
58
|
+
|
59
|
+
d.dept_name,
|
60
|
+
|
61
|
+
d.dept_address
|
62
|
+
|
63
|
+
from (
|
64
|
+
|
65
|
+
select *
|
66
|
+
|
67
|
+
,(select dept_id from user_rel_table
|
68
|
+
|
69
|
+
where user_id=u.id order by kubun limit 1) as dept_id
|
70
|
+
|
71
|
+
from users_table u
|
72
|
+
|
73
|
+
) uv
|
74
|
+
|
75
|
+
left join dept_table d
|
76
|
+
|
77
|
+
on d.id=uv.dept_id
|
78
|
+
|
79
|
+
```
|