0

如果我向子查询添加不同的,那么它会带来不同的行还是多行..??

我有一个查询,我收到错误

Subquery returns more than 1 row 

查询是这样的

SELECT DISTINCT(o.order_id), (SELECT DISTINCT op.vendor_id FROM order_product op 
WHERE op.order_id = o.order_id) AS vendor_id, CONCAT(o.firstname, ' ', o.lastname) 
AS customer, CONCAT(o.shipping_address_1, o.shipping_address_2, o.shipping_city,',',
o.shipping_zone,',',o.shipping_country,'-',o.shipping_postcode) AS address, 
(SELECT os.name FROM order_status os WHERE os.order_status_id = o.order_status_id
AND os.language_id = '1') AS status, (SELECT delivery_boy_name FROM delivery_boys db
WHERE o.delivery_boy_id = db.delivery_boy_id) as delivery_boy, o.delivery_boy_id, 
o.order_status_id, o.total, (SELECT SUM(op.total) FROM order_product op WHERE 
op.order_id = o.order_id AND op.vendor_id = '37') AS total, (SELECT os.cost FROM 
order_shipping os WHERE os.order_id = o.order_id AND os.vendor_id = '37') AS 
shipping_cost, o.currency_code, o.currency_value, o.date_added, o.date_modified 
FROM `order` o LEFT JOIN `order_product` op ON (o.order_id = op.order_id) WHERE 
o.order_status_id > '0' AND op.vendor_id = '37' AND 
DATE(o.date_added) = DATE('2012-10-11') AND o.order_status_id NOT IN (6,7) 
ORDER BY o.date_added DESC

对不起,查询太长了..我得到的错误是因为第二个子查询就是这个

(SELECT DISTINCT op.vendor_id FROM order_product op 
WHERE op.order_id = o.order_id) AS vendor_id

在上面的子查询中,我的目标是从 order_product 表中获取 vendor_id,并且一个 order_id 将具有相同的 vendor_id,这就是为什么我添加了 distinct 但 mysql 仍然给出了多行错误。

我怎样才能改变这个查询..?? 提前致谢。

4

2 回答 2

1

"distinct" does not cause the query to necessarily return only one row. "distinct" says to eliminate duplicate rows. So if, to make a simple example, you had a table with one column, and you had four records with values 1, 2, 2, and 3, then select without distinct would return four rows: 1, 2, 2, and 3. select distinct would return three rows: 1, 2, and 3.

Your query is fairly complex so I'm not sure just what you're trying to accomplish. You could force the subquery to return only one row by saying "select ... limit 1". Or you could replace all the fields in the select clause -- in this case just vendor_id I guess, with an aggregate, like select max(vendor_id). More likely, you need to add additional restrictions to the where clause so only one record will meet the conditions.

If you're expecting there to be only one qualifying record, but really there is more than one, then the problem is your data and not the query. If there can be more than one, than you need to figure out which one you want and modify the query to only get that one.

于 2012-10-11T15:19:58.930 回答
0

Distinct will always return multiple rows. you can either perform an inner join on some condition to restrict your rows or filter the rows on another specific condition.

于 2012-10-11T15:23:28.353 回答