我有以下表格:
Table a +-------+------------------+------+-----+ | Field | Type | Null | Key | +-------+------------------+------+-----+ | bid | int(10) unsigned | YES | | | cid | int(10) unsigned | YES | | +-------+------------------+------+-----+
Table b +-------+------------------+------+ | Field | Type | Null | +-------+------------------+------+ | bid | int(10) unsigned | NO | | cid | int(10) unsigned | NO | | data | int(10) unsigned | NO | +-------+------------------+------+
当我想从b中选择a中相应的bid / cid-pair的所有行时,我只使用自然连接SELECT b.* FROM b NATURAL JOIN a;一切都很好.
当a.bid或a.cid为NULL时,我想获得另一列匹配的每一行,例如如果a.bid是NULL,我想要a.cid = b.cid的每一行,如果两者都是NULL我想要b中的每一列.
我天真的解决方案是这样的:
SELECT DISTINCT b.* FROM b JOIN a ON ( ISNULL(a.bid) OR a.bid=b.bid ) AND (ISNULL(a.cid) OR a.cid=b.cid )
有没有更好的方法来做到这一点?
解决方法
不,这就是它.
(我通常将ISNULL(a.bind)改为a.bind IS NULL,用于ANSI sql合规性FWIW.)