我遇到一个#1137 - Can't reopen table: 't1'
错误
我下面有示例代码
CREATE TEMPORARY TABLE temp_table ( INDEX(productName),INDEX(age))
AS
select productName,age from productsmarket Inner Join customer on productsmarket.customer_username = customer.username;
select distinct t1.productName, (
select age
from temp_table t2
where t2.productName = t1.productName
group by age
order by count(*) desc
limit 1
)
as age
from temp_table t1
我想返回两列productName
和age
答案 0 :(得分:0)
我认为您不需要创建临时表(或永久表)来执行此操作。密集等级函数(在mysql 8 up中更容易实现),但在此处进行了模拟。
drop table if exists productsmarket;
CREATE table productsmarket (productname varchar(3),customer_username int);
insert into productsmarket values
('aaa',4),('aaa',2),('aaa',4),
('bbb',1),('bbb',4);
和客户
+------+------+------+
| id | name | age |
+------+------+------+
| 1 | abc | 10 |
| 2 | def | 10 |
| 3 | ghi | 10 |
| 4 | jkl | 11 |
| 5 | jkl | 11 |
+------+------+------+
5 rows in set (0.04 sec)
select productname,age,obs,
if(productname <> @p, @rn:=1,if(obs <> @po,@rn:=@rn+1,@rn:=@rn)) denserank,
@p:=productname pname,
@po:=obs po
from
(
select productName,age,count(*) obs
from productsmarket
Inner Join customer on productsmarket.customer_username = customer.id
group by productName,age
) s
cross join (select @rn:=0,@p:=0,@po:=0) r
having denserank = 1
order by productname,obs desc
;
+-------------+------+-----+-----------+-------+----+
| productname | age | obs | denserank | pname | po |
+-------------+------+-----+-----------+-------+----+
| aaa | 11 | 2 | 1 | aaa | 2 |
| bbb | 10 | 1 | 1 | bbb | 1 |
| bbb | 11 | 1 | 1 | bbb | 1 |
+-------------+------+-----+-----------+-------+----+
密集级别在平局时很有用。