Mysql 连接查询返回重复行

标签 mysql

SELECT m.*
     , p.image_url
     , r.acceptance_status
  from playermessage m
  join playerprofile p
    on p.player_id = m.sender_id 
  join requesttempstorage r
    on r.requester_id = m.sender_id  
 where m.player_id = 48

这个查询表现得很奇怪,它给了我两个重复的行,但是当我检查表playermessage时,没有重复的行,只有这个查询会向用户显示相同的消息两次,而只有一条消息任何人都可以发现错误。


| player_id | player_message                                          | date_sent           | sender_id | image_url          | acceptance_status |<br>
+-----------+---------------------------------------------------------+---------<br>------------+-----------+--------------------+-------------------+<br>
|        48 | imran wants to be a part of the pakistan cricket team   | 2018-05-17 18:58:08 |        50 | uploads/imran.jpg  |                 1 |<br>
|        48 | fakhar wants to be a part of the pakistan cricket team  | 2018-05-17 19:13:27 |        51 | uploads/fakhar.jpg |                 1 |<br>
|        48 | shadab wants to be a part of the pakistan cricket team  | 2018-05-18 11:09:49 |        52 | uploads/shadab.jpg |                 1 |<br><strong>
|        48 | asif wants to be a part of the pakistan cricket team    | 2018-05-18 11:20:51 |        53 | uploads/asif.jpeg  |                 0 </strong>|<br>
<strong>|        48 | asif wants to be a part of the pakistan cricket team    | 2018-05-18 11:20:51 |        53 | uploads/asif.jpeg  |                 0 |</strong><br>
+-----------+---------------------------------------------------------+---------------------+-----------+-----------------

问题在于最后两个结果(例如。),当所有另一条消息只有一个时,它返回两条消息,为什么它要这样做到最后两个结果。

最佳答案

这两个查询之一将返回两行:

 SELECT p.* FROM playerprofile p WHERE p.player_id = 53 

 SELECT r.* FROM requesttempstorage r WHERE r.requester_id = 53 
<小时/>

JOIN 操作查找所有 匹配的行,并返回所有这些行。

如果 playermessage 中有一行 sender_id = 53,并且

如果 playerprofile 中有行且 player_id = 53,那么我们预计行是返回。

如果 playerprofile 中有 行且 player_id = 53,那么连接操作将返回行。

如果 playerprofile 中有 0player_id = 53,那么我们将不会获得从 playermessage 返回的任何行sender_id = 53

<小时/>

如果 requesttempstorage 中还有两行 requester_id = 53,那么返回的行数也会加倍

playermessage 中的所有列都将在每一行上重复。

这正是内连接操作的设计方式。

关于Mysql 连接查询返回重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415117/

相关文章:

mysql - SQL 仅返回特定年龄的人

mysql - 重置 MySQL 管理员密码? (其他解决方案似乎不起作用)

mysqlslap : [ERROR] mysqlslap: Option 'debug-info' used, 但被禁用

mysql - 2 个来自同一个表的外键

PHP 从函数返回一个字符串供稍后使用?

MySQL 查询时间太长——索引应该是什么?

mysql - 创建过程时出错

php - 将表与子查询结果连接起来

mysql - 将mysql查询从一个时期扩展到多个时期

php - 选择 30 个随机行,其中总金额 = x