简体   繁体   English

选择来自TableA(如果存在,则为TableB)的值

[英]SELECT values from TableA (and TableB if exists)

I have a table product_checklist which holds checklist items. 我有一个表product_checklist ,其中包含检查清单项目。 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 我想一直抓住它,但是如果表ap_checklists的ap_id存在任何列表项,那么抓住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. 如果您未在group by中指定列或在汇总中指定列,则MySQL本质上会获取列的随机值。 If you use max it's guarantueed to pick a non-null value if available: 如果使用max则保证选择一个非空值(如果可用):

max(`ap_checklists`.`created_date`)

Where is wrong - ap_checklists . 哪里有问题ap_checklists ap_id = 195 should read ap_id = 195应该读

`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 您的where子句有一个错误,因为您使用的是左联接表,因此不应

If you whant to write it in standar sql it should be: 如果您想用标准SQL编写它,则应为:

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: 在Oracle的SQL中,您可以将其编写为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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