简体   繁体   中英

How to use sql GROUP BY clause on two columns?

I have 2 Mysql tables :

station :

在此处输入图片说明

logger :

在此处输入图片说明

Using this sql query it's showing following result :

$getStation = mysqli_query($conn, "SELECT st.st_tbl_id, st.st_name, st.st_address, st.st_lat, st.st_long, st.created,
GROUP_CONCAT(lg.lg_name) AS lg_name 
FROM station AS st 
LEFT JOIN logger AS lg ON lg.lg_id = st.lg_id 
GROUP BY st.st_name, st.st_id, st.lg_id 
ORDER BY st.st_tbl_id DESC");

在此处输入图片说明

Here you can see station name is duplicate value but it's should be unique one. Like for this scenario it's should be Comilla and Dhaka

See https://stackoverflow.com/a/2421441/347565

In your case, those entries have different lg_id, so they won't be grouped together. I think you just change your query to only group by st.st_id and you'll get the results you want.

Try this:

$getStation = mysqli_query($conn, "SELECT st.st_name, st.st_address, st.st_lat, st.st_long, st.created,
GROUP_CONCAT(lg.lg_name) AS lg_name 
FROM station AS st 
LEFT JOIN logger AS lg ON lg.lg_id = st.lg_id 
GROUP BY st.st_name,st.st_address,st.st_lat, st.st_long, st.created");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM