2017-07-14 215 views
0

時,我有以下3個表MySQL查詢錯誤:加入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' 

而且我收到以下錯誤:

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

+2

然後你會得到錯誤的結果。好工作,@UlugToprak – fancyPants

+0

閱讀更多關於['GROUP BY'](https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html) – axiac

+0

那麼我該如何解決它? – droidnation

回答

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(),您可以使用它來代替聚合函數。但正如名字所暗示的那樣,它會返回組的任何值。

+0

那麼我該如何解決它? – droidnation

+0

編輯我的答案。 – fancyPants

+0

這是新的嗎?我兩年前從來沒有這樣做過。這種改變意味着什麼? – droidnation