我有4个表必须连接在一个以上的字段上,并且当表3没有数据时无法使其工作
T1
self.assertQuerysetEqual(queryset_1, map(repr, queryset_2))
T2
id primary key
user_id
mydata
T3
id primary key
user_id
entry_id
mydata
T4
id primary key
user_id
entry_id
mydata
我想返回所有T1,其中搜索字符串与其他3个表中的任何一个匹配:
id primary key
user_id
entry_id
mydata
当所有表都有条目时查询有效,但是当说T3没有与entry_id匹配的条目时,则不返回任何内容。
我做错了什么,我似乎无法解决这个问题......请帮忙
答案 0 :(得分:0)
我设法通过用WHERE替换AND来解决问题,所以这个:
SELECT DISTINCT(id) as id FROM T1
LEFT JOIN T2 ON (T1.user_id = T2.user_id AND T2.entry_id = T1.id)
LEFT JOIN T3 ON (T1.user_id = T3.user_id AND T3.entry_id = T1.id)
LEFT JOIN T4 ON (T1.user_id = T4.user_id AND T4.entry_id = T1.id)
AND (T1.mydata LIKE :s OR T2.mydata LIKE :s OR T3.mydata LIKE :s OR T4.mydata LIKE :s)
变为:
SELECT DISTINCT(id) as id FROM T1
LEFT JOIN T2 ON (T1.user_id = T2.user_id AND T2.entry_id = T1.id)
LEFT JOIN T3 ON (T1.user_id = T3.user_id AND T3.entry_id = T1.id)
LEFT JOIN T4 ON (T1.user_id = T4.user_id AND T4.entry_id = T1.id)
WHERE (T1.mydata LIKE :s OR T2.mydata LIKE :s OR T3.mydata LIKE :s OR T4.mydata LIKE :s)
似乎AND导致搜索条件成为最后一个左连接的一部分。