Skip to content
Advertisement

sqlite return same value on left join

in below my sqlite command i want to get count of barcoeds when that’s equals with sessions.id

select sessions.id, sessions.session_name, sessions.session_type,sessions.date_time, count(barcodes.id) as barcode_count 
from sessions left join barcodes
on sessions.id = barcodes.session_id
group by barcodes.id
order by sessions.id desc

this command works, but that return more data with same value, for example if data is one, that return more than 3, but really i have one row

0 = {_List} size = 5
 0 = 11
 1 = "111"
 2 = 2
 3 = "1398/05/14 ساعت:  08:43"
 4 = 1
1 = {_List} size = 5
 0 = 11
 1 = "111"
 2 = 2
 3 = "1398/05/14 ساعت:  08:43"
 4 = 1
2 = {_List} size = 5
 0 = 11
 1 = "111"
 2 = 2
 3 = "1398/05/14 ساعت:  08:43"
 4 = 1

Advertisement

Answer

I think you want one row per session. So, your query is aggregating by the wrong column:

select s.id, s.session_name, s.session_type,
       s.date_time, count(b.id) as barcode_count 
from sessions s left join
     barcodes b
     on s.id = b.session_id
group by s.id
---------^ sessions not barcode
order by s.id desc;

You might find this also easy to do with a correlated subquery:

select s.*,
       (select count(*) from barcodes b where b.session_id = s.id)
from sessions s;

The use of table aliases in these queries makes them easier to write and to read.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement