我有疑问:
SELECT
cl.id client_id,
c.provider_id provider_id,
c.mcc mcc,
c.mnc mnc,
c.cost cost,
c.active active_cost
FROM costs c
INNER JOIN clients cl
ON cl.pref_provider_id = c.provider_id
WHERE c.mcc = 405 AND c.mnc = 11 AND c.active = 1 AND cl.id = 2
如果在适当的条件下找不到这条记录,我需要写第二个SELECT并尝试通过这个条件得到记录(WHERE c.mcc = 405 AND c.mnc = 0 AND c.active = 1 AND cl.id = 2)在一个查询中,当然
能帮帮我吗?尽可能少地查询它是理想的:)
答案 0 :(得分:1)
您可以使用NOT EXISTS()来检查是否存在mnc = 11
的记录 SELECT
cl.id client_id,
c.provider_id provider_id,
c.mcc mcc,
c.mnc mnc,
c.cost cost,
c.active active_cost
FROM costs c
INNER JOIN clients cl
ON cl.pref_provider_id = c.provider_id
WHERE c.mcc = 405 AND c.active = 1 AND cl.id = 2
AND (c.mnc = 11 or
c = 0 and NOT EXISTS(select 1 from costs cc
where cc.mcc = 405 AND cc.active = 1 AND
and cc.mnc = 11 and cl.pref_provider_id = cc.provider_id ))
答案 1 :(得分:0)
SELECT
cl.id client_id,
c.provider_id provider_id,
c.mcc mcc,
c.mnc mnc,
c.cost cost,
c.active active_cost
FROM (select * from costs LIMIT 100 OFFSET 1) c
INNER JOIN clients cl
ON cl.pref_provider_id = c.provider_id
WHERE c.mcc = 405 AND c.mnc = 11 AND c.active = 1 AND cl.id = 2;
答案 2 :(得分:0)
试试这个:
SELECT cl.id client_id,
case when c1.provider_id is not null then c1.provider_id else c2.provider_id end provider_id,
case when c1.mcc is not null then c1.mcc else c2.mcc end mcc,
case when c1.mnc is not null then c1.mnc else c2.mnc end mnc,
case when c1.cost is not null then c1.cost else c2.cost end cost,
case when c1.active is not null then c1.active else c2.active end active_cost
FROM clients cl
left outer join costs c1 ON cl.pref_provider_id = c1.provider_id and c1.mcc = 405 AND c1.mnc = 11 AND c1.active = 1
left outer join costs c2 ON cl.pref_provider_id = c2.provider_id and c2.mcc = 405 AND c2.mnc = 0 AND c2.active = 1
where AND cl.id = 2
and (c1.provider_id is not null or c2.provider_id is not null)