在union子句中返回错误

时间:2014-11-29 15:12:23

标签: mysql union

我使用这个查询它没有订购数据但是在通过查询添加订单后返回错误

(SELECT * FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN new_cards
WHERE new_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND new_cards.`Sup_ID`  = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND new_cards.`Bill_ID` = bills.`Bill_ID`)
UNION
(SELECT * FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN sold_cards WHERE
sold_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND sold_cards.`Sup_ID`  = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND sold_cards.`Bill_ID` = bills.`Bill_ID`)
ORDER BY bills.`ID` DESC

这是错误     表'账单'其中一个SELECT不能用于全局ORDER子句

1 个答案:

答案 0 :(得分:1)

首先,我建议您选择列名。这样,您就知道两个查询都返回相同数量的列。然后你可以ORDER BY ID DESC

要让您的工作正常,请在每个联合中标识bill id列,然后按顺序排序(不引用表名):

(SELECT bills.id billsid, <<other columns>> FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN new_cards
WHERE new_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND new_cards.`Sup_ID`  = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND new_cards.`Bill_ID` = bills.`Bill_ID`)
UNION
(SELECT bills.id billsid, <<other columns>> FROM bills INNER JOIN cats INNER JOIN suppliers
INNER JOIN sold_cards WHERE
sold_cards.`Card_Code` LIKE '%8%'
AND bills.`Sup_ID` = suppliers.`Sup_ID`
AND sold_cards.`Sup_ID`  = suppliers.`Sup_ID`
AND cats.`Cat_ID` = bills.`Cat_ID`
AND bills.`Cat_ID` = cats.`Cat_ID`
AND sold_cards.`Bill_ID` = bills.`Bill_ID`)
ORDER BY billsid DESC

就个人而言,我建议您按如下方式重写您的查询:

SELECT b.id billsid, other columns 
FROM bills b
    INNER JOIN cats c ON c.`Cat_ID` = b.`Cat_ID`
    INNER JOIN suppliers s ON b.`Sup_ID` = s.`Sup_ID`
    INNER JOIN new_cards nc ON nc.`Sup_ID`  = s.`Sup_ID` 
                               AND nc.`Bill_ID` = b.`Bill_ID`
WHERE nc.`Card_Code` LIKE '%8%'
UNION
SELECT b.id billsid, other columns
FROM bills b 
    INNER JOIN cats c ON c.`Cat_ID` = b.`Cat_ID`
    INNER JOIN suppliers s ON b.`Sup_ID` = s.`Sup_ID`
    INNER JOIN sold_cards sc ON sc.`Sup_ID`  = s.`Sup_ID` 
                              AND sc.`Bill_ID` = b.`Bill_ID`
WHERE sc.`Card_Code` LIKE '%8%'
ORDER BY billsid DESC