dragonsun00000 2018-12-03 11:28
浏览 45

在内部联接查询PHP + MySQL上查找具有相同名称的用户

I'm working on a search system very outdated in PHP+MySQL, now... The owner asked me to introduce two buttons to apply filters to the main query. First button should find only users with same first_name and last_name, the second one should find only users with same last_name. Now ATM the query uses different joins (inner and left do get other informations from other tables)

$query = "
  SELECT s1.*,s2.first_name,s2.last_name,s2.email,s2.id as subscriber_id,s2.phone,s2.info,a.id as agency_id,a.info as agency_info,a.invoice as agency_invoice
  FROM subscription as s1
  LEFT JOIN agency as a
  ON s1.agency=a.id
  INNER JOIN subscriber as s2
  ON s1.subscriber=s2.id
  WHERE $matches AND s1.deleted=0
  ORDER BY s1.id DESC
  LIMIT $maxid,$limit
";

Everything works properbly but if I add clauses to group users by same full_name it returns only one result per fullname...

So if I have a table like this

+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Foo        | Bar       |
| Foo        | Bar       |
| Bar        | Foo       |
| Bar        | Foo       |
| John       | Doe       |
+------------+-----------+

It returns

+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Foo        | Bar       |
| Bar        | Foo       |
+------------+-----------+ 

Now... the clauses that I add into query are these (count and groupby)

$query = "
  SELECT s1.*,s2.first_name,s2.last_name,s2.email,s2.id as subscriber_id,s2.phone,s2.info,a.id as agency_id,a.info as agency_info,a.invoice as agency_invoice, Count(s2.*) AS Cnt
  FROM subscription as s1
  LEFT JOIN agency as a
  ON s1.agency=a.id
  INNER JOIN subscriber as s2
  ON s1.subscriber=s2.id
  WHERE $matches AND s1.deleted=0
  GROUP BY s2.first_name, s2.last_name HAVING Cnt>1
  ORDER BY s1.id DESC
  LIMIT $maxid,$limit
";

But as I've already said... it doesn't work and I don't know why... where am I wrong? Does it depend from joining? Is there a way to find a solution or with that query I need to find another solution? Please help me, I've tried other solutions but no way! :D

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 Revit2020下载问题
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数