Mysql query on the issue of the connection between the table and the table

Three connections

One : two tables is one to one relationship, such as the number 01 only one reported in Table 1 and Table 2, in reality, extremely rare

Many : as a record number 01 appears in Table 1, and the two even many records appear in Table 2, the more common business reality

Many to many : As the name suggests, with a record number appears more than once in each of the two tables, business is rare, personal experience, if taken in this way join queries lead to double counting, inconsistent with the actual business case, an error.

For many-to-case example:
Electricity supplier data ER diagram
Title: Let find the strongest purchasing power of the top ten cities
appear in the table orderinfo city and useraddress, between two tables by userid userinfo may correspond to them, pay attention to an arrow pointing to more than that userinfo user (userid) is one, how can a pen in orderinfo orders orderid, the userid on orderid to correspond with, there will be many times; the same token, a userid may also have multiple recipients in the useraddress address, recipient address appears there are several several corresponding userid. Indeed orderInfo user, address useraddress the same, and if orderInfo useraddress join query through shared userid field, typical-many connection, orderInfo in each record is the same userid useraddress respectively all the same userid connector, i.e. cross-connection is repeated, the same addresses are addresses different from a corresponding connector, the results inconsistent with the actual error. Orderinfo can directly query, see the code:

select b.city,sum(OrderAmount) c from orderinfo a join
	useraddress b on a.userid=b.userid  	-- 错误写法,此为多对多,重复计算
    group by b.city
    order by c desc
    limit 10;
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200129135441875.png)

The results are as follows:
Here Insert Picture Description

--正确写法:
select city,sum(OrderAmount) c from orderinfo
    group by city
    order by c desc
    limit 10;

The results are as follows:
Here Insert Picture Description

Published an original article · won praise 0 · Views 7

Guess you like

Origin blog.csdn.net/reed_rxs/article/details/104105854