【问题标题】:How to get last record group by join query in two table如何通过两个表中的连接查询获取最后一个记录组
【发布时间】:2018-08-18 19:19:21
【问题描述】:

这是我的模态查询

SELECT COUNT(IF(n.status='0',1, NULL)) as counter, n.notify_from, n.notify_to,  n.status, n.notify_text, n.notify_id, n.notify_type, n.notify_time, r.user_name, r.user_image, r.user_gender FROM `notifications` AS n JOIN register r ON n.`notify_from` = r.unique_user_name WHERE n.`notify_to` = 'IzaazG' AND n.`notify_type` = '6' GROUP BY n.`notify_from` ORDER BY n.`notify_id` DESC

从此查询中我无法从通知表中获取最后一条记录。

【问题讨论】:

  • “最后一个”是什么意思?结果是你得到了什么,而不是你想要得到什么? “模态查询”是什么意思?
  • 我正在使用 codeigniter,为什么我使用了 modal 这个词,第二个是最后一条记录意味着我无法获得通知表的 MAX id..谢谢。

标签: mysql database codeigniter


【解决方案1】:

从函数 COUNT 中删除 IF 条件 并尝试使用 case 语句

【讨论】:

  • 我用过 * ,查询给出的结果相同。
  • n.notify_from, n.notify_to, n.status, n.notify_text, n.notify_id, n.notify_type, n.notify_time, r.user_name, r.user_image, r.user_gender 请把这个group by 中的列不包括计数
  • @AizazGull 如果我理解正确:您正试图从 notify_from 列中获取 notif 的数量?如果您只想要数字,则不需要将所有列放在 select 中。你只需要那里的功能,如果你想显示你正在分组的列的文本,也将该列放在选择中。但请记住,选择语句中的每一列也应该在 group by 上,但聚合函数除外。算在你的情况下
  • 如果你想要第二次尝试这种方式 _______ 使用 cte(max,nr) 作为 (select n.notify_from, n.notify_to, n.status, n.notify_text, n.notify_id, n. notify_type, n.notify_time, r.user_name, r.user_image, r.user_gender ,ROW_NUMBER()over (order by n.notify_id desc) FROM notifications AS n JOIN register r ON n.notify_from = r. unique_user_name WHERE n.notify_to = 'IzaazG' AND n.notify_type = '6' ) select * from cte where nr = 2
猜你喜欢
  • 2013-06-13
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
相关资源
最近更新 更多