sql - SQL多表连接查询字符串中有DISTINCT关键字时如何查询记录数
问题描述
我使用 SQL Server,我的 SQL 命令是:
select distinct
table_motor.motor_ID, table_welding_machine.welding_machine_ID
from
table_motor,
table_welding_machine,
table_joint_point_para,
table_motor_production_line
where
table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID
and table_joint_point_para.motor_ID = table_motor.motor_ID
and table_motor_production_line.motor_ID = table_motor.motor_ID
and 1=1
结果中有 83 条记录。
DISTINCT
我的问题是: SQL多表联合查询字符串中有关键字时如何查询记录数?
如果我在字符串中使用 count ,我会收到错误:
列 table_motor.motor_ID 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
如果我像这样更改我的 SQL 命令,我不会得到记录的总数:
select distinct
table_motor.motor_ID,
table_welding_machine.welding_machine_ID,
count(*)
from
table_motor,
table_welding_machine,
table_joint_point_para,
table_motor_production_line
where
table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID
and table_joint_point_para.motor_ID = table_motor.motor_ID
and table_motor_production_line.motor_ID = table_motor.motor_ID
and 1=1
group by
table_motor.motor_ID, table_welding_machine.welding_machine_ID
如何解决这个问题呢?
这个字符串没问题:
select count(distinct (t_test01.tid)) from t_test01, t_test02 where t_test01.tid = t_test02.tid
这个字符串是错误的:',' 附近的语法不正确。
select count(distinct (t_test01.tid, t_test02.value)) from t_test01, t_test02 where t_test01.tid = t_test02.tid
解决方案
试试这个查询:
select * , count(*) as CountOfRecords from (
select distinct
table_motor.motor_ID,
table_welding_machine.welding_machine_ID
from
table_motor,
table_welding_machine,
table_joint_point_para,
table_motor_production_line
where
table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID
and table_joint_point_para.motor_ID = table_motor.motor_ID
and table_motor_production_line.motor_ID = table_motor.motor_ID
and 1=1
group by
table_motor.motor_ID, table_welding_machine.welding_machine_ID
) as d group by d.motor_ID, d.welding_machine_ID
推荐阅读
- laravel - Laravel api auth:sanctum 是否可以用于 ajax 请求(非 spa 网站)
- database - MongoDB 从多个文档中提取子文档数组值
- python - 如何将 X min, Y sec 字符串转换为时间戳
- docker - 覆盖网络首先创建的泊坞窗在哪里,在经理或工人上?
- wordpress - wordpress 上 mailgun 插件的严重错误
- reactjs - 如何将默认反应上下文值设置为来自 Firestore 的数据?
- google-chrome - 为什么加载 mp3 广播流时 Google Chrome 会延迟?
- swiftui - 使用 SwiftUI 使用解码的 JSON 初始化 Struct
- python - 如何序列化购物车对象?
- spring-boot - 某些属性未从服务器加载