![](/img/trans.png)
[英]sql join issue, not able to retrieve records from table a which matches some condition in table b and remaining left out table a records
[英]sql join issue, not able to retrieve records from table a which matches some condition in table b and all that Ids that present in table A
我正在編寫一個 sql 查詢來從表 A 中獲取所有那些與特定條件匹配的表 b 的記錄,以及表 a 中所有匹配的記錄 下面是代碼和表
Table A
skey OrderName
100 Pen
100 Cutter
101 any
Table b1
skey Key Count
100 True 2
SELECT distinct gmo.Skey,
gmo.orderName
from Test_B gmc
inner join Test_A gmo
on gmc.Skey=gmo.Skey
where gmc.Count >1 and gmo.orderName in ('Cutter')
我需要的結果是
skey Ordername Default
100 Cutter True
100 Pen
我只想用一個查詢來做到這一點,請幫忙
使用左連接 - DEMO
SELECT A.Skey,A.orderName
from A
left join B
on A.Skey=B.Skey
where B.Skey is not null
內連接很好,只是將條件移動到選擇,排序可能是一個問題。
SELECT gmo.Skey,
gmo.orderName,
CASE WHEN gmc.CountS > 1 and gmo.orderName in ('Cutter') THEN GMC.KEYVAL ELSE '' END `default`
from T1 gmc
inner join T gmo on gmc.Skey=gmo.Skey
+------+-----------+---------+
| Skey | orderName | default |
+------+-----------+---------+
| 100 | Pen | |
| 100 | Cutter | True |
+------+-----------+---------+
2 rows in set (0.001 sec)
btw default 是一個保留字,需要反引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.