mysql count problems
SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1, table_2 AS t2
WHERE t1.`group` = 'val'
AND t2.code = 'val'
returns
count - normal value
special_value - NULL
but
SELECT t2.special_valu开发者_运维知识库e
FROM table_2 AS t2
WHERE t2.code = 'val'
returns
special_value - another normal value
why first query works wrong?..
currently, i need
(count( t1.id ) + t2.special_value)
This is why you should never use SQL'89 implicit join syntax.
You have no join condition resulting in a cross join.
Rewrite the query using explicit join syntax:
SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1
INNER JOIN table_2 AS t2 ON (t1.`group` = t2.code) <<-- join condition here
WHERE .... <<-- filter condition here
GROUP BY .... <<-- group by field here
I don't know how table t1 and t2 are linked, so you'll have to tweak this a bit, but that's how it supposed to work.
And please never ever use implicit where
joins again.
Remarks
I'm wondering what p.`group`
and pp.code
are, but I'm guessing you meant to write t1.`group`
and t2.code
You only need to escape fields and tablenames in `
backticks if they are reserved words.
Personally all those backticks make me dizzy, but that's just me.
精彩评论