我有以下 3 个表:
我需要设置一个 HTML 表格来显示以下内容:
<tr class="bg-info">
<th>Med ID</th>
<th>Med Name</th>
<th>Med Expiry</th>
<th>Barcode</th>
<th>Number of Tablets received</th>
<th>Total Number of Pills received</th>
<th>Date Received</th>
<th>Pills distributed</th>
<th>Still (in tablets)</th>
<th>Still (in pills)</th>
</tr>
所以我创建了这个 SQL 查询:
select t1.med_id,
t3.med_name,
t1.med_expiry,
t1.med_barcode,
t1.med_tablet,
t1.med_pill,
t1.med_received,
sum(t2.given_quantity)
FROM med_pharmacy t1, consultation_med t2, medication t3 WHERE t1.med_pharmacy_id = t2.med_pharmacy_id AND t1.med_id=t3.med_id
AND t1.clinic_id='361'
我收到以下错误:
Error Code: 1140. In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'ncd.t1.med_id'; this is incompatible with sql_mode=only_full_group_by
最佳答案
您使用的GROUP BY
错误。规则是 SELECT
子句中的每一列要么也在您的 GROUP BY
子句中,要么必须应用聚合函数(如 count、min、max、avg)它。
sql_mode ONLY_FULL_GROUP_BY 可以防止这种情况发生。当您禁用它时会发生什么,可以在这个问题中看到:Why i get Null values in my second counter using case statement
解决方案也可以在链接的问题中找到。此处重复一遍:应用聚合函数或将列包含在 group by 子句中。
您可以像这样修复它:
select t1.med_id,
t3.med_name,
t1.med_expiry,
t1.med_barcode,
t1.med_tablet,
t1.med_pill,
t1.med_received,
sum(t2.given_quantity)
FROM med_pharmacy t1, consultation_med t2, medication t3 WHERE t1.med_pharmacy_id = t2.med_pharmacy_id AND t1.med_id=t3.med_id
AND t1.clinic_id='361'
group by
t1.med_id,
t3.med_name,
t1.med_expiry,
t1.med_barcode,
t1.med_tablet,
t1.med_pill,
t1.med_received
或者像这样
select
MAX(t1.med_id),
MAX(t3.med_name),
MAX(t1.med_expiry),
MAX(t1.med_barcode),
MAX(t1.med_tablet),
MAX(t1.med_pill),
MAX(t1.med_received),
sum(t2.given_quantity)
FROM med_pharmacy t1, consultation_med t2, medication t3 WHERE t1.med_pharmacy_id = t2.med_pharmacy_id AND t1.med_id=t3.med_id
AND t1.clinic_id='361'
或两者的组合,具体取决于您的需求。
当您使用 MySQL 5.7 时,还有新函数 any_value()您可以使用它来代替聚合函数。但正如名称所示,它返回该组的任何值。
关于连接3个表时MySQL查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45099329/