You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL多表关联查询:获取带销售位置的产品记录并排序

SQL查询报错:SELECT语句列数不一致(关联表并排序需求)

我有一个存储产品记录和销售位置数据的数据库,需要返回整合不同表数据的数据集。尝试了以下SQL代码:

SELECT 't1' 
productdate, 
productcode, 
productdescription, 
productqty, 
producttotal 
FROM history_product WHERE productdate='2024/07/02'
UNION ALL
SELECT 't2' 
barcodenumber, 
salelocation 
FROM producttable WHERE barcodenumber='t1.productcode';

收到SQL错误(1222):使用的SELECT语句列数不一致。

需求是通过history_product表的productcode关联producttable表的salelocation,将其添加到产品记录结果末尾,并最终按salelocation对结果排序。


原history_product表数据

productdateproductcodeproductdescriptionproductqtyproducttotal
2024/07/021004NUMATIC HENRY REFURB [W/ KIT]542997
2024/07/021012DYSON V7 CORDLESS114999
2024/07/021017VACUUM CLEANER SERVICE14900
2024/07/025030017989345CARPET SHAMPOO 1.5 LITRES11199
2024/07/025053197108184NUMATIC HENRY SMS BAGS X51699
2024/07/02746984912341VAC AIR FRESHER SUMMER MEADOW 6PK1199

目标结果(添加location列)

productdateproductcodeproductdescriptionproductqtyproducttotallocation
2024/07/021004NUMATIC HENRY REFURB [W/ KIT]5429970004
2024/07/021012DYSON V7 CORDLESS1149990004
2024/07/021017VACUUM CLEANER SERVICE149000001
2024/07/025030017989345CARPET SHAMPOO 1.5 LITRES111990002
2024/07/025053197108184NUMATIC HENRY SMS BAGS X516990005
2024/07/02746984912341VAC AIR FRESHER SUMMER MEADOW 6PK11990002

排序后结果

productdateproductcodeproductdescriptionproductqtyproducttotallocation
2024/07/021017VACUUM CLEANER SERVICE149000001
2024/07/02746984912341VAC AIR FRESHER SUMMER MEADOW 6PK11990002
2024/07/025030017989345CARPET SHAMPOO 1.5 LITRES111990002
2024/07/021004NUMATIC HENRY REFURB [W/ KIT]5429970004
2024/07/021012DYSON V7 CORDLESS1149990004
2024/07/025053197108184NUMATIC HENRY SMS BAGS X516990005

错误原因及解决方案

错误原因

UNION ALL要求前后两个SELECT语句返回的列数完全一致,且对应列的数据类型兼容。你的第一个SELECT返回了6列('t1' + 5个产品字段),第二个SELECT只返回了3列('t2' + barcodenumber + salelocation),列数不匹配导致报错。此外,WHERE barcodenumber='t1.productcode'的写法错误,会把t1.productcode当作字符串常量,而非关联字段。

正确SQL代码

要实现关联表并添加位置列,应该用JOIN而非UNION ALL。如果需要保留所有产品记录(即使没有对应位置),用LEFT JOIN;如果只保留有位置的产品,用INNER JOIN:

SELECT 
    hp.productdate,
    hp.productcode,
    hp.productdescription,
    hp.productqty,
    hp.producttotal,
    pt.salelocation AS location
FROM history_product hp
LEFT JOIN producttable pt ON hp.productcode = pt.barcodenumber
WHERE hp.productdate = '2024/07/02'
ORDER BY pt.salelocation;

如果salelocation是字符串类型,排序会按字典序(符合示例结果);如果是数值类型,会按数值大小排序,可根据实际字段类型调整。


内容的提问来源于stack exchange,提问作者Andrew Gable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:22:19