【问题标题】:SQL statement to get all the users获取所有用户的SQL语句
【发布时间】:2015-02-08 05:26:15
【问题描述】:

我有这张表,我很困惑如何生成关于如何获取 ALL u_id 的 sql 语句,它在 p_id 下作为父 ID。

如果只需要 5 作为 p_id,这是我想要的输出。

users       usernames       p_id
7           miller           5
8           jamie            5
9           honey            7
10          jack             7

gather_table

p_id        u_id

null         1
1            5
1            6
5            7
5            8
7            9
7            10

用户表

user_id      user_name

1            millan
2            john
3            max
4            chris
5            jane
6            lester
7            miller
8            jamie
9            Honey
10           Jack

提前谢谢你。

编辑:

我试过 >=6 但它返回 9 和 10,但 6 在我的收集表中从来不是 p_id,所以它在我的收集表上没有 u_id。

我想获取属于它的 p_id 的所有 u_id (p_id)。在我的示例中,5 的 p_id 为 7 8 9 10,尽管 9 和 10 的 p_id 为 7,但 7 的 p_id 为 5,所以它们仍低于 5

【问题讨论】:

标签: php mysql sql


【解决方案1】:

您可以为此目的使用左连接

SELECT `g`.`p_id`, `u`.* FROM `gather_table` as `g` LEFT JOIN `user_table` as `u` ON `g`.`u_id` = `u`.`user_id` WHERE `g`.`p_id` >= 5

更新:

您可以查看Finding all parents in mysql table with single query (Recursive Query)的答案

但是如果每个u_id只有一个父级,那么我建议你使用嵌套集表结构,这是处理这类问题的更优雅的方式。在这种情况下,表结构就像

CREATE TABLE IF NOT EXISTS `user_table` (
  `u_id` int(11) NOT NULL AUTO_INCREMENT,
  `p_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
  `lft` int(11) NOT NULL DEFAULT '0',
  `rgt` int(11) NOT NULL DEFAULT '0',
  `level` int(10) UNSIGNED NOT NULL DEFAULT '0',
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`u_id`),
  KEY `idx_left_right` (`lft`,`rgt`)
) DEFAULT CHARSET=utf8;

你可以参考这个article。这是 Joomla 特有的,但可能会有所帮助。

【讨论】:

  • 我有话要说,如果 >= 6 but 6 在我的gather_table中没有u_id怎么办
  • 那么它应该返回空结果。
  • 好的。是的,我的错。它将返回 9、10 的记录。根据您的情况,这是正确的。在这种情况下你想要什么?
  • 我需要更改我的用户表吗?你发布的那个?
  • 我对如何插入关卡感到困惑
【解决方案2】:
select t1.user_id ,t1.user_name,t2.p_id from user as t1 
inner join gather as t2 on t1.user_id = t2.u_id
where t2.p_id >= 5

您想要的输出显示您想要 p_id >= 5。尝​​试加入查询 查看documentation了解更多信息

【讨论】:

  • 如果 >=6 怎么办?但是 6 在我的gather_table 中从来没有 p_id 它没有 u_id,但我尝试了你的解决方案它返回 9 和 10
  • 是的,如果您尝试使用 >= 6,它将返回 9,10,因为 7 是唯一 >= 6 的 p_id。那有什么问题?
【解决方案3】:

在你的桌子上使用连接:

SELECT gather_table.p_id, user_table.* FROM gather_table  LEFT JOIN user_table ON gather_table.u_id = user_table.user_id WHERE gather_table.p_id = 5

【讨论】:

    【解决方案4】:

    希望对你有帮助

    select g.u_id,g.p_id,u.user_name from gather_table g,user_table u where g.u_id=u.user_id and g.u_id>=7
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2015-02-24
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      相关资源
      最近更新 更多