[英]Multiple inner joins with different where-conditions
I am currently using the following query to perform a search across multiple tables via INNER JOIN. 我目前正在使用以下查询通过INNER JOIN跨多个表执行搜索。
SELECT title, m2.txt1 AS teaser, inputdat, db_file.*
FROM db_item
INNER JOIN db_itemv AS m1 USING(id_item)
INNER JOIN db_itemf USING(id_item)
INNER JOIN db_itemd USING(id_item)
INNER JOIN db_itemv AS m2 USING(id_item)
WHERE type=15 AND m1.fldnr='12'
AND m1.indik='b' AND m1.txt1s='en'
AND visibility=0 AND inputdat>'2005-11-02' AND m2.fldnr='123'
GROUP BY title
ORDER BY inputdat DESC
LIMIT 0,100
The columns of db_itemv (m1, m2) are named: db_itemv(m1,m2)的列命名为:
ID id_item fldnr indik txt1
One id_item may exist on several rows. 一个id_item可能存在于多行上。
My problem is, that m2.fldnr='123' does not always exist and therefore it kicks out the whole row. 我的问题是,m2.fldnr ='123'并不总是存在,因此它会踢出整行。 But I want to keep the row and keep the column empty when it doesn't exist in the row.
但是我想保留行并在行中不存在时将列保持为空。 How can I solve the problem?
我该如何解决这个问题?
用left outer join
替换所有inner join
left outer join
I think there are a couple of issues here, so bear with me whilst I go through them :) 我觉得这里有几个问题,所以当我经历它们时,请忍受我:)
I agree with @Jeurgen that you need to use LEFT JOIN
instead of INNER JOIN
, which will enable you to retrieve all the rows that you are searching for, including those without an entry in m2
. 我同意@Jeurgen你需要使用
LEFT JOIN
而不是INNER JOIN
,这将使你能够检索你要搜索的所有行,包括那些没有m2
条目的行。
However, as your where clause specifically states only give me that data which DOES HAVE an m2.fldnr
value equal to '123', then it is correct for you not to have any rows which do not having matching m2
rows, as they cannot meet your criteria. 但是,正如你的where子句明确说明只给我那个
m2.fldnr
值等于'123'的数据,那么你没有任何行没有匹配的m2
行是正确的,因为它们不能满足你的标准。
I think what you are trying to do is pull all data from the first four tables, and then only data within the m2
table that contains '123', if this is the case, then you need to relocate your m2.fldnr
filter, and handle those missing rows... 我想你要做的是从前四个表中提取所有数据,然后只包含
m2
表中包含'123'的数据,如果是这种情况,那么你需要重新定位你的m2.fldnr
过滤器,并且处理那些丢失的行......
My version of your query is thus as follows - this has not been tested, as I don't have sample data with your structure, but give it a try, and vary it if needed; 我的查询版本如下所示 - 这尚未经过测试,因为我没有结构的示例数据,但试一试,如果需要可以改变它;
SELECT title, m2.txt1 AS teaser, inputdat, db_file.*
FROM db_item
INNER JOIN db_itemv AS m1 USING(id_item)
INNER JOIN db_itemf USING(id_item)
INNER JOIN db_itemd USING(id_item)
LEFT JOIN db_itemv AS m2
ON db_item.id_item = m2.id_item
AND ( m2.fldnr = '123' OR m2.fldnr IS NULL )
WHERE type=15
AND m1.fldnr = '12'
AND m1.indik = 'b'
AND m1.txt1s = 'en'
AND visibility = 0
AND inputdat > '2005-11-02'
GROUP BY title
ORDER BY inputdat DESC
Hope that helps :) 希望有帮助:)
我认为你应该使用LEFT JOIN
而不是INNER JOIN db_itemv AS m2
,即使db_itemv
返回NULL也应该返回所有其他数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.