简体   繁体   中英

SELECT values from TableA (and TableB if exists)

I have a table product_checklist which holds checklist items. I want to grab this at all times, but if any list items exist for the ap_id in the table ap_checklists then grab created_date

The current statement below needs some kind of priority on the where's maybe? is it possible to do this in one query?

SELECT 
    `product_checklists`.*, 
    `ap_checklists`.`ap_id`,
    `ap_checklists`.`created_date`
FROM (`product_checklists`)
LEFT OUTER JOIN 
    `ap_checklists` ON `product_checklists`.`check_id` = `ap_checklists`.`check_id`
WHERE 
    `ap_checklists`.`ap_id` = 195 OR `product_id` = 3
GROUP BY 
    `product_checklists`.`check_process` ORDER BY `product_checklists`.`check_order`

If you don't specify a column in the group by or an aggregate, MySQL essentially grabs a random value for a colum. If you use max it's guarantueed to pick a non-null value if available:

max(`ap_checklists`.`created_date`)

Where is wrong - ap_checklists . ap_id = 195 should read

`product_checklists`.`ap_id` = 195

because you filtered right side of left join and that effectively transforms left join to inner join.

You have an bug on your where clause, because you are using a left joined table and you shouldn't

If you whant to write it in standar sql it should be:

FROM (`product_checklists`)     
LEFT OUTER JOIN `ap_checklists` ON `product_checklists`.`check_id` = ap_checklists`.`check_id` AND (`ap_checklists`.`ap_id` = 195 OR `product_id` = 3)

In Oracle's SQL you can write it as:

 FROM `product_checklists`, `ap_checklists` 
WHERE  `product_checklists`.`check_id` =(+) `ap_checklists`.`check_id`
  AND (`ap_checklists`.`ap_id` (+)= 195 OR `product_id` = 3)

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