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

时间:2018-12-03 11:28:54

标签: php mysql search group-by inner-join

我正在使用PHP + MySQL进行过时的搜索系统,现在...所有者要求我引入两个按钮以将过滤器应用于主查询。第一个按钮应仅查找具有相同first_name和last_name的用户,第二个按钮应仅查找具有相同last_name的用户。 现在,ATM查询使用不同的联接(内部和左侧确实从其他表中获取其他信息)

$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
";

一切正常,但是如果我通过相同的full_name向子用户添加子句,则每个全名仅返回一个结果...

所以,如果我有这样的桌子

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

返回

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

现在...我添加到查询中的子句是这些(count和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
";

但是正如我已经说过的那样...它不起作用,我也不知道为什么...我在哪里错了?是否取决于加入?有没有找到解决方案的方法,或者使用该查询我需要找到其他解决方案?请帮助我,我尝试了其他解决方案,但是没有办法! :D

0 个答案:

没有答案