Mysql左连接返回多行

时间:2015-10-22 11:05:47

标签: php mysql left-join

我有3张桌子和一些字段'名字是一样的。这是第一个名为 semp 的表:

enter image description here

第二个名字 semp_k

enter image description here

第三个是 semp_y

enter image description here

你看,主表是第一个,其他的是相关的。第一张表有3行。因此,当我获取它时,它必须返回3行。但是当我获取第一个表时,它会将返回的行与第二个和第三个表的总和相乘。这是我的代码:

SELECT s.*, k.*, y.* FROM semp AS s LEFT JOIN semp_k AS k ON s.no = k.semp_no LEFT JOIN semp_y AS y ON s.no = y.semp_no WHERE s.durum = 1 ORDER BY s.bas_t DESC

2 个答案:

答案 0 :(得分:1)

使用MySQL group by

group by s.no

或试试这个: -

SELECT
s.*, k.*, y.*
FROM
semp AS s
LEFT JOIN semp_k AS k ON s. NO = k.semp_no
LEFT JOIN semp_y AS y ON s. NO = y.semp_no
WHERE
s.durum = 1
GROUP BY s.no
ORDER BY
s.bas_t DESC

答案 1 :(得分:1)

您需要使用分组依据。 你的查询应该是这样的;

SELECT
    s.*, k.*, y.*
FROM
    semp AS s
LEFT JOIN semp_k AS k ON s. NO = k.semp_no
LEFT JOIN semp_y AS y ON s. NO = y.semp_no
WHERE
    s.durum = 1
GROUP BY s.no
ORDER BY
    s.bas_t DESC