mysql left join returns unexpected amount of rows

感情迁移 提交于 2019-12-24 10:49:37

问题


I have 2 tables where

tableA has 41 rows

and

tableB has 3 rows

I am trying to get the total rows of these 2 tables via a query using left join but i get way more rows(123) than expected(44)

query:

SELECT COUNT(*)
    FROM tableA as u
LEFT JOIN tableB as d
    ON u.uid=d.uid
WHERE
    u.uid=912391178669
    AND
    u.deleted = 0
    AND
    d.deleted=0

tables schema:

tableA

id | uid | deleted

tableB

id | uid | deleted


回答1:


I have run the following query It is working correctly.. U can check it out.

SELECT 
  ( SELECT count(*) from table1 where.... )
+ ( SELECT count(*) from table2 where.... )
as total from dual



回答2:


I'm guessing that you have three rows in tableA with the uid given in the query. That will mean that each row in tableA will join once with each row in tableB, which means you will back 41 x 3 rows or 123.

From the number of rows you are expecting back, I wonder if you need a Union instead of a join.

Select * from tableA where uid = 912391178669 and deleted = 0

union all

Select * from tableB where uid = 912391178669 and deleted = 0

A union will combine the results of two queries. A join will combine the columns of table tables in a single query.




回答3:


41*3=123

each row of TableA has uid=912391178669 and tableB each row also have uid that's why you are getting 123 row total. use some filter criteria to get desired result (like some AND condition)

if you can show us your table column then it may be possible to help you .

Left join does not combine the rows of two table .
TableA left join TableB will give you all the row of table A meeting the joining condition.




回答4:


SELECT COUNT(*)
FROM tableA as u
LEFT JOIN tableB as d
ON u.uid=d.uid
AND
u.deleted = d.deleted
WHERE
u.uid=912391178669
AND u.deleted = 0



回答5:


SELECT SUM(
  (SELECT count(*) from tableA WHERE uid=912391178669)
+ (SELECT count(*) from tableA WHERE uid=912391178669)
 ) as totalRows


来源:https://stackoverflow.com/questions/10344923/mysql-left-join-returns-unexpected-amount-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!