在优化查询方面需要帮助

时间:2019-06-09 19:42:04

标签: mysql

查询1:

select min(transaction_id) 
from Customer_transaction_info 
where customer_id in (
  select customer_id from Customer_transaction_info
) 
group by cuisine,customer_id

此查询将为我提供有关客户什么时候第一次点菜的信息。

查询2:

select min(transaction_id) 
from Customer_transaction_info 
where customer_id in (
  select customer_id from Customer_transaction_info
) 
group by city,customer_id

此查询将为我提供有关客户何时在城市订购的信息。

查询3: 我想基于查询1和query2编写一个包含列First_time_to_cityFirst_time_to_cuisine的查询。这将是这样的:

select 
  transaction_id, customer_id, transaction_time, 
  if(transaction_id in (QUERY1),TRUE,FALSE) as First_time_to_cuisine,
  if(transaction_id in (QUERY2),TRUE,FALSE) as First_time_to_city

请让我知道是否可以优化查询。

1 个答案:

答案 0 :(得分:-1)

此:

where customer_id in (
  select customer_id from Customer_transaction_info
)

完全没有用,因为:
customer_id中的每个Customer_transaction_infocustomer_id中的Customer_transaction_info!对吧?
您可以将表加入两个查询:

select 
  t.transaction_id, t.customer_id, t.transaction_time,
  case when c1.firsttimetocuisineid is null then 'FALSE' else 'TRUE' end First_time_to_cuisine, 
  case when c2.firsttimetocity is null then 'FALSE' else 'TRUE' end First_time_to_city
from Customer_transaction_info t
left join (
  select
    cuisine, customer_id, 
    min(transaction_id) firsttimetocuisineid 
  from Customer_transaction_info 
  group by cuisine, customer_id
) c1 on c1.cuisine = t.cuisine and c1.customer_id = t.customer_id and c1.firsttimetocuisineid = t.transaction_id
left join (
  select
    city, customer_id,
    min(transaction_id) firsttimetocityid
  from Customer_transaction_info 
  group by city, customer_id
) c2 on c2.city = t.city and c2.customer_id = t.customer_id and c2.firsttimetocityid = t.transaction_id