【发布时间】:2016-07-21 06:49:54
【问题描述】:
我有两张桌子。 我想从第一个表中获取最新的 updated_product_id 如果存在于第二个表中 else product_id。 我有第一个表 sr_client_products
id | product_id| client_id
1 | 1 | 1
第二个表 sr_client_product_updates
id | product_id| updated_product_id | client_product_id| updated_date
1 | 1 | 2 | 1 | 2016-02-03
2 | 2 | 4 | 1 | 2016-06-07
**预期输出:单行列
updated_product_id = 4 as of updated_date
如果第二个表 sr_client_product_updates 没有值,那么
product_id = 1 from first table
.** 到现在查询
SELECT
if(ProductUpdate.updated_product_id = '',
(select ClientProduct.product_id from sr_client_products ClientProduct where ClientProduct.client_id=1),
ProductUpdate.updated_product_id)
as product_id
from sr_client_product_updates ProductUpdate where ProductUpdate.client_product_id=1 order by ProductUpdate.updated_date DESC limit 1
上述查询的问题是如果第二个表中存在值则显示数据,否则返回空,我认为问题还在于 where 查询 输出: product_id = 4 如果数据存在于第二个表中 别的 如果第二个表为空,product_id =1
已编辑查询:
SELECT
if(count(*) = 0,
(select ClientProduct.product_id from sr_client_products ClientProduct where ClientProduct.client_id=1),
ProductUpdate.updated_product_id)
as product_id
from sr_client_product_updates ProductUpdate
where ProductUpdate.client_product_id=1
order by ProductUpdate.updated_date DESC limit 0,100
@Philipp 提供的解决方案
SELECT
COALESCE (
sr_client_product_updates.updated_product_id,
sr_client_products.product_id
) AS id
FROM
sr_client_products
LEFT JOIN (
SELECT
MAX(updated_date) AS update_date,
client_product_id
FROM
sr_client_product_updates
GROUP BY
client_product_id
) AS lastUpdate ON lastUpdate.client_product_id = sr_client_products.id
LEFT JOIN sr_client_product_updates ON sr_client_product_updates.client_product_id = lastUpdate.client_product_id
AND sr_client_product_updates.updated_date = lastUpdate.update_date where sr_client_products.id=1
【问题讨论】:
-
您对此样本数据的预期结果是什么?
-
product_id = 4 如果数据存在于第二个表中 else product_id =1 如果第二个表为空
-
需要澄清一下
标签: mysql