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表数据
| productdate | productcode | productdescription | productqty | producttotal |
|---|---|---|---|---|
| 2024/07/02 | 1004 | NUMATIC HENRY REFURB [W/ KIT] | 5 | 42997 |
| 2024/07/02 | 1012 | DYSON V7 CORDLESS | 1 | 14999 |
| 2024/07/02 | 1017 | VACUUM CLEANER SERVICE | 1 | 4900 |
| 2024/07/02 | 5030017989345 | CARPET SHAMPOO 1.5 LITRES | 1 | 1199 |
| 2024/07/02 | 5053197108184 | NUMATIC HENRY SMS BAGS X5 | 1 | 699 |
| 2024/07/02 | 746984912341 | VAC AIR FRESHER SUMMER MEADOW 6PK | 1 | 199 |
目标结果(添加location列)
| productdate | productcode | productdescription | productqty | producttotal | location |
|---|---|---|---|---|---|
| 2024/07/02 | 1004 | NUMATIC HENRY REFURB [W/ KIT] | 5 | 42997 | 0004 |
| 2024/07/02 | 1012 | DYSON V7 CORDLESS | 1 | 14999 | 0004 |
| 2024/07/02 | 1017 | VACUUM CLEANER SERVICE | 1 | 4900 | 0001 |
| 2024/07/02 | 5030017989345 | CARPET SHAMPOO 1.5 LITRES | 1 | 1199 | 0002 |
| 2024/07/02 | 5053197108184 | NUMATIC HENRY SMS BAGS X5 | 1 | 699 | 0005 |
| 2024/07/02 | 746984912341 | VAC AIR FRESHER SUMMER MEADOW 6PK | 1 | 199 | 0002 |
排序后结果
| productdate | productcode | productdescription | productqty | producttotal | location |
|---|---|---|---|---|---|
| 2024/07/02 | 1017 | VACUUM CLEANER SERVICE | 1 | 4900 | 0001 |
| 2024/07/02 | 746984912341 | VAC AIR FRESHER SUMMER MEADOW 6PK | 1 | 199 | 0002 |
| 2024/07/02 | 5030017989345 | CARPET SHAMPOO 1.5 LITRES | 1 | 1199 | 0002 |
| 2024/07/02 | 1004 | NUMATIC HENRY REFURB [W/ KIT] | 5 | 42997 | 0004 |
| 2024/07/02 | 1012 | DYSON V7 CORDLESS | 1 | 14999 | 0004 |
| 2024/07/02 | 5053197108184 | NUMATIC HENRY SMS BAGS X5 | 1 | 699 | 0005 |
错误原因及解决方案
错误原因
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
相关产品推荐
相关产品推荐

