加入3个表时MySQL查询错误

时间:2017-07-14 09:24:46

标签: mysql sql join

我有以下3个表:

enter image description here

我需要设置一个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'

我收到以下错误:

  

错误代码:1140。在没有GROUP BY的聚合查询中,表达式为#1   SELECT列表包含非聚合列'ncd.t1.med_id';这是   与sql_mode = only_full_group_by

不兼容

1 个答案:

答案 0 :(得分:2)

您使用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()而不是聚合函数。但是顾名思义,它会返回该组的任何值。