我正在尝试在python中编写一个迭代脚本,根据他们是否满足查询表中的条件,可以看到为客户分配一个id。通常情况下,我会使用sql join完成此操作,但是我需要一个过程脚本来查看它们是否满足查找中存在的条件,然后为它们分配id。某些属性不是必需的或可用的,因此sql join不起作用,因为连接将要求满足所有条件。请参阅下面的示例:
客户表
customer attr1 attr2 attr3
jerry a r g
tom q e h
cindy c f j
id_lookup表
id attr1 attr2 attr3
1 a (null) g
2 (null) e h
3 c f (null)
最终输出
customer id
jerry 1
tom 2
cindy 3
请注意,jerry在attr1和attr3上匹配,因此符合条件,因此被分配1.脚本移动到下一个客户,以程序方式分配id,从1开始并按升序继续。
在sql中,我会写
select a.customer
, b.id
from customers a
join id_lookup b
on ( a.attr1 = b.attr1
and a.attr2 = b.attr2
and a.attr3 = b.attr2 )
但是,某些属性不可用,并且由于客户可能匹配许多ID,因此可能无法为其分配一次权限,因为应为客户分配具有其符合条件的最低值的ID。
python中是否有可以实现此目的的脚本?
答案 0 :(得分:1)
您可以在SQL中执行此操作。
select a.name
, min(b.id)
from customers a
join id_lookup b
on ( (a.attr1 = b.attr1 or b.attr1 is null)
and (a.attr2 = b.attr2 or b.attr2 is null)
and (a.attr3= b.attr3 or b.attr3 is null) )
group by a.name;
我确定您也可以在Python中解决问题,但这需要在ORM中编写等效项(因此任何解决方案都取决于您使用的ORM)或将整个表加载到Python中并在那里处理它们,如果你的桌子很大,这将是不切实际的。