mysql 查询结果太多,多表MySQL查询返回太多结果

I need to do a SELECT in 8 tables, but the results in not what I have expected.

The ugly code:

SELECT equipment.*

FROM equipment

LEFT JOIN equip_adaptador a ON (a.cod_equip = equipment.cod_equip)

LEFT JOIN equip_antena aa ON (aa.cod_equip = equipment.cod_equip)

LEFT JOIN equip_cable c ON (c.cod_equip = equipment.cod_equip)

LEFT JOIN equip_conector cc ON (cc.cod_equip = equipment.cod_equip)

LEFT JOIN equip_fonte f ON (f.cod_equip = equipment.cod_equip)

LEFT JOIN equip_router r ON (r.cod_equip = equipment.cod_equip)

LEFT JOIN equip_suporte s ON (s.cod_equip = equipment.cod_equip)

WHERE equipment.cod_equip = 'EC726026316A0'

the results is 63 items, is not right.

Explainig the code above:

My table equipment is my master table, there I have the cod_equip field (a master field to all my slave tables).

All my slave table I had gave a prefix called equip_ (are 7 slave tables in the total)

Now I need a SELECT to JOIN all the 8 tables.

Adding more:

I was expecting 9 rows, but it fetched 63 rows, I need to show something like this: table equipment (only 1 row) and other tables the respect number of it owns.

For example equip_adaptador was two times inserted with the same cod_equip, then I need to show it..

This query is the same as if I do one by one query to see what I have with the equipment.cod_equip = 'EC726026316A0'

Just it!

Thanks in advance people!

解决方案

What's happening is that each row returned from a child table is matched with every row returned from the other child tables.

You have one parent row returned, as you expect.

But if one of the child tables has seven (7) matching rows, and another child table has nine (9) matching rows, you are getting 7*9=63 rows returned.

This is the expected resultset, per the SQL specification.

Here is a test case that demonstrates what is happening:

CREATE TABLE t (id INT);

CREATE TABLE c1 (id INT, t_id INT);

CREATE TABLE c2 (id INT, t_id INT);

INSERT INTO t VALUES (1);

INSERT INTO c1 VALUES (11,1),(12,1);

INSERT INTO c2 VALUES (21,1),(22,1);

SELECT t.id, c1.id AS c1, c2.id AS c2

FROM t

JOIN c1 ON (t.id = c1.t_id)

JOIN c2 ON (t.id = c2.t_id)

id c1 c2

-- --- ---

1 11 21

1 12 21

1 11 22

1 12 22

Note that the rows from c1 are repeated, once for each row from c2. Likewise for the rows from c2.

This is exactly the result set we expect.

If we don't want a cross join (cartesian product) of the child rows, we can run separate queries:

SELECT t.id, c1.id AS c1

FROM t

JOIN c1 ON (t.id = c1.t_id)

SELECT t.id, c2.id AS c2

FROM t

JOIN c2 ON (t.id = c2.t_id)

id c1

-- ---

1 11

1 12

id c2

-- ---

1 21

1 22

That's one way to avoid generating "repeated" child rows.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值