MySQL中GROUP BY优先
我有以下查询。
$query_assignments = "SELECT * FROM tb_scheduler_assignments
WHERE company_id = '".$company_id."' OR
dept_id = '".$dept_id."' OR
user_id = '".$user_id."' ORDER BY
due_date GROUP BY purchase_id";
我想要的是一个单一的查询解决方案,可以保留 user_id
的结果超过 dept_id
和 dept_id
超过 company_id
>。
例如:
- 如果出现相同的
purchase_id
通过dept_id
获取的行以及user_id
,那么我只想要结果 对于user_id
; - 如果出现相同的
purchase_id
通过company_id
获取的行 和user_id
,那么我只想要user_id
的结果
I have the following query.
$query_assignments = "SELECT * FROM tb_scheduler_assignments
WHERE company_id = '".$company_id."' OR
dept_id = '".$dept_id."' OR
user_id = '".$user_id."' ORDER BY
due_date GROUP BY purchase_id";
What I'd like is a single query solution that would keep the results for user_id
over dept_id
and dept_id
over company_id
.
For example:
- if the same
purchase_id
occurs for
rows that were gotten viadept_id
anduser_id
, then I only want the result
for theuser_id
; - if the same
purchase_id
occurs for
rows that were gotten viacompany_id
anduser_id
, then I only want the
result for theuser_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您在 SQL 中插入变量,这表明您可能容易受到 SQL 注入的攻击。只是为了确定一下。 PHP 应该提供准备好的语句或一些转义函数。
其次,您的 SQL 语句将无法编译,因为您使用的是 GROUP BY a,但选择了至少还包含三列的
*
。第三,听起来您误解了 SQL,认为它可能在您尝试制定的查询中(不使用 UNION ALL)检索重复的行,即多次检索同一行因为它符合多个条件。事实并非如此。
First, you're interpolating variables in your SQL, which suggests you might be vulnerable to SQL injection. Just to make sure. PHP should offer prepared statements, or some escaping function.
Second, your SQL statement won't compile because you're using
GROUP BY a
but selecting*
which includes at least three more columns.Third, it sounds like you're misunderstanding SQL in thinking that it might, in a query such as you're trying to formulate (without
UNION ALL
), retrieve duplicate rows, i.e. the same row multiple times because it matches multiple criteria. This is not so.我正在寻找的“单一查询”解决方案似乎不存在,或者如果存在,它会比仅仅处理 php 中的所有排序慢得多。
因此,我运行了 3 个单独的查询,将每个查询放入数组中,然后为了将它们全部放入具有我需要的层次结构的最终数组中,我执行了下面的循环来查看购买 ID 是否存在于更高级别等级制度。如果没有,那么我将其放入数组中。
然后我可以按照我想要的方式对该数组进行排序,并循环遍历它以回显我需要的内容。
不确定这是否是最好的方法,但它效果很好,而且对我来说快如闪电。
The "single query" solution that I was looking for doesn't seem to exist, or if it does, it would be way slower than just handling all the sorting in php.
So, I ran 3 separate queries, put each of them into arrays, and then in order to put them all into a final array with the hierarchy that I needed, I did the loops below to see if the purchaseID existed for the levels up the hierarchy. If it didn't, then I put it in to the array.
Then I can sort that array however I want and loop through that to echo what I need to.
Not sure if that's the best way, but it worked well and is lightning fast for me.
您可以使用
if
语句创建虚拟字段。警告:无法编制索引!
语法修复:
GROUP BY
和ORDER BY
重新排序You can make a virtual field with the
if
statement.WARNING: can not be Indexed!
Syntax FIX:
GROUP BY
andORDER BY
reordered