简体   繁体   中英

mysql left join after inner join gives wrong record set

SELECT  
    op.sub_order_id, 
    s.supplier_id, 
    GROUP_CONCAT(opb.box_id SEPARATOR ','),
    op.delivery_country

FROM 
    order_p op
INNER JOIN 
    supplier s ON s.supplier_id = op.supplier_name
LEFT JOIN
    order_boxes opb ON op.sub_order_id = opb.sub_order_id
WHERE
    op.order_active=0
    AND op.ship_date>='2013-01-01'
    AND op.ship_date<='2013-04-24'
ORDER BY op.ship_date DESC

I am not very good at joins, so bear with me.

I have this query where I need to select all data from order table between the given date range, such that a matching supplier mapping exists in the supplier table. Now along with this info, I need to also fetch any boxes, if it exists in the order_boxes table linked by sub_order_id fields.

Now, if I just join the order and supplier tables, I get the correct record-set of about 1000 records, but as soon as I try to add in the boxes table, I get only one row. I am guessing this happens because there is only one record in the boxes table, but I need it to fetch all records from order table along with the box table. If I try INNER JOIN instead of LEFT JOIN I get only 1 record of the matching suborder as mapped in the box table, but with Left join, I get the first record within the date range, irrespective of the sub_order_id and the value in the boxes table.

Please help. Also if you need any more info, please let me know.

EDIT : I am sorry I didn't post the full thing before, but I think the problem is with GROUP_CONCAT, which groups the entire recordset where as I want to only group the records in the boxes table....maybe I should use a subquery?

Current output

179-1  |  2  |  2,4,3 |  Canada

Expected output

168-1  |  1  |        |  Texas
.....
......
179-1  |  2  |  2,4,3 |  Canada
.....
......
SELECT * FROM
(
  SELECT  * FROM order op INNER JOIN 
  supplier s ON s.supplier_id = op.supplier_name

  WHERE
    op.order_active=0
    AND op.ship_date>='2013-01-01'
    AND op.ship_date<='2013-04-24'
  ORDER BY op.ship_date DESC
) AS a 

LEFT JOIN order_boxes opb ON a.sub_order_id = opb.sub_order_id

Try this and tell me whether this help you or not.

Try Converting Date

 WHERE
op.order_active=0
AND op.ship_date>=
convert(datetime,cast('2013-01-01' as varchar),101)
AND op.ship_date<=
convert(datetime,cast('2013-04-24' as varchar),101)
                        ORDER BY op.ship_date DESC

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