如何以laravel方式组合两个查询
Posted
技术标签:
【中文标题】如何以laravel方式组合两个查询【英文标题】:how to combine two queries in larvel way 【发布时间】:2021-10-12 20:34:43 【问题描述】:我有 3 张桌子:
tb_user
tb_addquestion
tb_answer
以下查询返回每个用户的问题计数 (query 1
) 和每个用户的答案 (query 2
)。我需要将结果合并到一个输出中。
如何在单个查询的帮助下实现这一目标?
每位用户的问题数 (query1)
SELECT tb_addquestion.userid,
COUNT(*) AS count
FROM tb_addquestion
LEFT JOIN tb_user
ON tb_user.userid = tb_addquestion.userid
GROUP BY tb_addquestion.userid
HAVING count > 0 AND
count < 15
每个用户的答案 (query2)
SELECT tb_answer.userid,
COUNT(*) AS count
FROM tb_answer
LEFT JOIN tb_user
ON tb_user.userid = tb_answer.userid
GROUP BY tb_answer.userid
HAVING count > 0 AND
count < 15
【问题讨论】:
抱歉,运行 2 个单独的查询有什么问题?如果将它们组合起来,它们仍将作为 2 个查询运行(如果可以组合它们)。 @matiaslauriti 您确定两个单独的查询(= 两个数据库请求)和一个组合查询(= 一个数据库请求)之间没有区别(在性能方面)吗? @AbsoluteBeginner 数据库性能将是相同的,或者将它们加入同一个查询中,将是最糟糕的...... 【参考方案1】:你可以使用UNION
:
SELECT tb_addquestion.userid,
COUNT(*) AS count,
'questions' AS type
FROM tb_addquestion
LEFT JOIN tb_user
ON tb_user.userid = tb_addquestion.userid
GROUP BY tb_addquestion.userid
HAVING count > 0 AND
count < 15
UNION
SELECT tb_answer.userid,
COUNT(*) AS count,
'answers' AS type
FROM tb_answer
LEFT JOIN tb_user
ON tb_user.userid = tb_answer.userid
GROUP BY tb_answer.userid
HAVING count > 0 AND
count < 15
【讨论】:
【参考方案2】:通常我们会在单独的子查询中执行聚合,然后将主表连接到每个子查询:
SELECT
u.userid,
COALESCE(aq.q_cnt, 0) AS q_cnt,
COALESCE(a.a_cnt, 0) AS a_cnt
FROM tb_user u
LEFT JOIN
(
SELECT userid, COUNT(*) AS q_cnt
FROM tb_addquestion
GROUP BY userid
HAVING q_cnt > 0 AND q_cnt < 15
) aq
ON aq.userid = u.userid
LEFT JOIN
(
SELECT userid, COUNT(*) AS a_cnt
FROM tb_answer
GROUP BY userid
HAVING a_cnt > 0 AND a_cnt < 15
) a
ON a.userid = u.userid
【讨论】:
以上是关于如何以laravel方式组合两个查询的主要内容,如果未能解决你的问题,请参考以下文章
如何从两个不同的 Laravel 查询构建器中获取我的两个结果集以同时显示在同一页面上?
Laravel查询以输出json数据作为选择列表。如何修改现有代码以连接两个值