我有2个表,例如:
表A包含数据:
id | name
-----------
1 | nik
表B包含字段:
id | id_a ( relation 1 to many to table A ) | name
---------------------------
3 | 1 | mark
4 | 1 | den
当我尝试向每个表发出sql请求时,我只有一行
# SQL from table A
SELECT * FROM A
WHERE A.id=1
# result is one line - 1 | nik
表B中的SQL
SELECT min(B.id) FROM B WHERE B.id_a = 1
# also return 1 line - 3 | 1 | mark
但是当我尝试使用LEFT JOIN执行sql-request时,我得到了2行
SELECT count(*) FROM A
LEFT JOIN B ON B.id = ( SELECT min(B.id) FROM B WHERE B.id_a = A.id )
WHERE A.id=1
#will return - 2
我很困惑,无法理解在这种情况下mysql的工作方式和工作方式。
答案 0 :(得分:0)
对不起。
解决方案是使用表别名。
SELECT count(*) FROM A
LEFT JOIN B ON B.id = ( SELECT min(b1.id) FROM B as b1 WHERE b1.id_a = A.id )
WHERE A.id=1
在子查询中添加表别名B as b1
,一切正常