美好的一天。 我有一个错误"使用的select语句具有不同数量的列mysql"
我的查询
SELECT
* FROM
inventory
WHERE
barcode1 = 'DR963560860GYYQBKBBD2'
OR barcode2 = 'DR963560860GYYQBKBBD2'
OR barcode3 = 'DR963560860GYYQBKBBD2'
OR barcode4 = 'DR963560860GYYQBKBBD2' UNION
SELECT
p.id AS 'PartId',
m.`Name` AS 'Model',
c.`Name` AS 'Color',
pt.`Name` AS 'PartType'
FROM
inventory i
JOIN part p ON p.Id = i.PartId
JOIN model m ON m.Id = p.ModelId
JOIN color c ON c.Id = p.ColorId
JOIN parttype pt ON pt.Id = p.PartTypeId
WHERE
barcode1 = @barcode
OR barcode2 = @barcode
OR barcode3 = 'DR963560860GYYQBKBBD2'
OR barcode4 = 'DR963560860GYYQBKBBD2';
我想得到的是第一个select语句中inventory表中的所有数据,另一个来自另一个表。
之前,我有两个查询
SELECT
*
FROM
inventory
WHERE
barcode1 = @Barcode
OR barcode2 = @Barcode
OR barcode3 = @Barcode
OR barcode4 = @Barcode`
将检索广告资源中的所有信息,另一个是
SELECT
p.id AS 'PartId',
m.`Name` AS 'Model',
c.`Name` AS 'Color',
pt.`Name` AS 'PartType'
FROM
inventory i
JOIN part p ON p.Id = i.PartId
JOIN model m ON m.Id = p.ModelId
JOIN color c ON c.Id = p.ColorId
JOIN parttype pt ON pt.Id = p.PartTypeId
WHERE
barcode1 = @Barcode
OR barcode2 = @Barcode
OR barcode3 = @Barcode
OR barcode4 = @Barcode
这只会加载四列。
由于我的输出加载太慢,我将在一个查询中将它组合在一起。这可能吗? 我怎么能这样做?
我是mysql的初学者,如果你能帮助我,我将非常感激。
谢谢你和Godbless。
答案 0 :(得分:1)
您遇到的问题是因为您在具有不同列数的两个表上使用Union
。例如,如果你在TableA中得到了什么:
| Id | Name | Age|
+----+------+----+
| 1 | Andy | 3 |
另一个TableB
| Id | Name | Age| Gender |
+----+------+----+--------|
| 1 | Andy | 3 | Male |
如果您尝试将它们联合起来,则会出现错误,因为它们无法合并(因为列数不同)。
所以你的问题是你的第一个Select *...
返回的列多于你只选择4列的第二个选择。解决它的关键是指定您需要选择哪些列,以便两个选择具有相同的列数。
像这样的东西
SELECT
p.id AS 'PartId',
m.`Name` AS 'Model',
c.`Name` AS 'Color',
pt.`Name` AS 'PartType'
FROM
inventory i
JOIN part p ON p.Id = i.PartId
JOIN model m ON m.Id = p.ModelId
JOIN color c ON c.Id = p.ColorId
JOIN parttype pt ON pt.Id = p.PartTypeId
WHERE
i.barcode1 = 'DR963560860GYYQBKBBD2'
OR i.barcode2 = 'DR963560860GYYQBKBBD2'
OR i.barcode3 = 'DR963560860GYYQBKBBD2'
OR i.barcode4 = 'DR963560860GYYQBKBBD2'
UNION
SELECT
p.id AS 'PartId',
m.`Name` AS 'Model',
c.`Name` AS 'Color',
pt.`Name` AS 'PartType'
FROM
inventory i
JOIN part p ON p.Id = i.PartId
JOIN model m ON m.Id = p.ModelId
JOIN color c ON c.Id = p.ColorId
JOIN parttype pt ON pt.Id = p.PartTypeId
WHERE
barcode1 = @barcode
OR barcode2 = @barcode
OR barcode3 = 'DR963560860GYYQBKBBD2'
OR barcode4 = 'DR963560860GYYQBKBBD2';
答案 1 :(得分:0)
当联接(水平合并)看起来更合适时,我不明白为什么要使用联合(即垂直合并)
SELECT i.*,
p.id AS 'PartId',
m.`Name` AS 'Model',
c.`Name` AS 'Color',
pt.`Name` AS 'PartType'
FROM
inventory i
JOIN part p ON p.Id = i.PartId
JOIN model m ON m.Id = p.ModelId
JOIN color c ON c.Id = p.ColorId
JOIN parttype pt ON pt.Id = p.PartTypeId
WHERE
barcode1 = @Barcode
OR barcode2 = @Barcode
OR barcode3 = @Barcode
OR barcode4 = @Barcode