【问题标题】:Why does this MySQL Query returns two rows?为什么这个 MySQL 查询返回两行?
【发布时间】:2011-04-29 06:25:35
【问题描述】:

我的查询返回两行,其中第二行与第一行完全相同。我想知道为什么会这样?我知道如果我把 LIMIT 1 放在最后,它只会返回一行,所以我会要求不要建议这个解决方案。这是我的查询

SELECT u.username,u.password,u.registerDate,u.lastVisitDate,u.lastVisitIp,
u.activationString,
u.active,u.block,u.contact_id,c.name,c.email,c.pPhone,c.sPhone,c.rPhone,c.area_id,
a.name as areaName, a.city_id, ct.name as cityName, ct.state_id, s.name as stateName, 
s.country_id, cn.name as countryName 
FROM users u 
LEFT JOIN contacts c 
ON (u.contact_id = c.id) 
LEFT JOIN areas a 
ON (c.area_id = a.id) 
LEFT JOIN cities ct 
ON (a.city_id = ct.id) 
LEFT JOIN states s 
ON (ct.state_id = s.id) 
LEFT JOIN countries cn 
ON (s.country_id = c.id) 
WHERE u.id = 1

以上查询正在从 6 个表中获取数据,其中包括

users s
contacts c
areas a
cities ct
states s
country cn

以上6个表都有主键id,外键如下

users.conntact_id
contacts.area_id
areas.city_id
cities.state_id
states.country_id

为什么它返回两行而不是一行?

【问题讨论】:

  • 您确定查询中的所有条件都是 1 行而不是 2 行吗?
  • 是的,我确定,users 表只有 1 条 id 为 1 的记录
  • 但可能在其他表中有 2 行用户 id=1 ???
  • @Harry 在任何表中都没有用户 id 的外键。

标签: mysql database


【解决方案1】:

您加入的其中一个表具有多个元素,因此所有其他表都会重复。这个表很可能是contacts 表。

【讨论】:

  • 很抱歉,我无法理解您到底想解释什么?
  • @Ibrahim - 如果contacts 表中有 2 条匹配记录,应该返回多少行?
  • @Oded 昨天才学会 JOIN :) LEFT JOIN 不应该返回结果只有当它从表 A 中找到匹配项时才返回结果。
  • @Ibrahim - 这将是其他表之一。遍历所有连接。
  • 啊啊,我知道了,我在有多个匹配项的区域有记录。现在我明白了原因.. 感谢 Oded 的解释对我有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多