Created
October 21, 2019 01:01
-
-
Save zzzeek/52ebb5bf6189564f4d09f9e56cbc24dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import Column | |
from sqlalchemy import create_engine | |
from sqlalchemy import ForeignKey | |
from sqlalchemy import Integer | |
from sqlalchemy import String | |
from sqlalchemy import Table | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import relationship | |
from sqlalchemy.orm import Session | |
Base = declarative_base() | |
atob = Table( | |
"atob", | |
Base.metadata, | |
Column("aid", ForeignKey("a.id"), primary_key=True), | |
Column("bid", ForeignKey("b.id"), primary_key=True), | |
) | |
class A(Base): | |
__tablename__ = "a" | |
id = Column(Integer, primary_key=True) | |
data = Column(String) | |
bs = relationship("B", secondary=atob) | |
class B(Base): | |
__tablename__ = "b" | |
id = Column(Integer, primary_key=True) | |
a_id = Column(ForeignKey("a.id")) | |
data = Column(String) | |
e = create_engine("sqlite://", echo=True) | |
Base.metadata.create_all(e) | |
s = Session(e) | |
s.add(A(bs=[B()])) | |
s.commit() | |
""" | |
SELECT a.id AS a_id, a.data AS a_data | |
FROM a | |
WHERE EXISTS (SELECT 1 | |
FROM atob, b | |
WHERE a.id = atob.aid AND b.id = atob.bid AND b.data = ?) | |
""" | |
print(s.query(A).filter(A.bs.any(B.data == "foo"))) | |
# mix outerjoin with any, could work like this, but I think this is the | |
# same result as above | |
""" | |
SELECT a.id AS a_id, a.data AS a_data | |
FROM a LEFT OUTER JOIN atob ON a.id = atob.aid | |
WHERE EXISTS (SELECT 1 | |
FROM b | |
WHERE a.id = atob.aid AND b.id = atob.bid AND b.data = ?) | |
""" | |
print( | |
s.query(A) | |
.outerjoin(atob) | |
.filter(A.bs.any(B.data == "foo").correlate(atob)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
search for A that has no B:
output: