sql query count(*)返回意外结果

时间:2013-12-30 22:19:54

标签: mysql sql select count

希望你圣诞快乐!

我的查询有问题,

我有这个查询

SELECT * , group_concat( tt.tradeID ) AS tradeArray
FROM tbl_tradesmen AS t
LEFT JOIN tbl_tradesmen_trades AS tt ON tt.tradesmenID = t.tradesmenID
LEFT JOIN tbl_trades AS trade ON trade.tradeID = tt.tradeID
LEFT JOIN tbl_tradesmen_location AS loc ON loc.tradesmenID = t.tradesmenID
LEFT JOIN tbl_locations AS l ON l.locationID = loc.locationID
GROUP BY t.tradesmenID

返回1条记录,这是我所期望的,因为我在tbl_tradesmen表中有1个商人。但是,这个商人在tbl_tradesmen_trades表中有2个交易,而group_concat字段包含这两个交易。

现在我想找出记录的数量,所以我认为最好的方法是为我的查询添加一个计数,如此

SELECT COUNT(*) , group_concat( tt.tradeID ) AS tradeArray
FROM tbl_tradesmen AS t
LEFT JOIN tbl_tradesmen_trades AS tt ON tt.tradesmenID = t.tradesmenID
LEFT JOIN tbl_trades AS trade ON trade.tradeID = tt.tradeID
LEFT JOIN tbl_tradesmen_location AS loc ON loc.tradesmenID = t.tradesmenID
LEFT JOIN tbl_locations AS l ON l.locationID = loc.locationID
GROUP BY t.tradesmenID

但这会返回一个2的计数值,而不是1,但我不知道为什么会这样或如何让它返回1。

任何帮助将不胜感激 感谢

1 个答案:

答案 0 :(得分:1)

试试这个,你会明白发生了什么

SELECT *
FROM tbl_tradesmen AS t
LEFT JOIN tbl_tradesmen_trades AS tt ON tt.tradesmenID = t.tradesmenID
LEFT JOIN tbl_trades AS trade ON trade.tradeID = tt.tradeID
LEFT JOIN tbl_tradesmen_location AS loc ON loc.tradesmenID = t.tradesmenID
LEFT JOIN tbl_locations AS l ON l.locationID = loc.locationID

您正在使用JOIN将交易者与交易合并,因此如果您的交易员是“Jon”并且交易1和2,您将获得以下内容:

Trader Trade
Jon    1
Jon    2

所以当你通过t.tradesmenID创建一个组时,你会得到1行,因为你只有1个商人,但是有2行所以Count给你的结果值为2

我希望这能帮到你,对不起我的英语。