1

我在编写 MYSQL 查询时几乎不需要帮助。

我想从 3 个表中检索数据,但只有在 count() 值等于 1 时,我才想从第 3 个表中检索数据。

请参阅以下查询。

SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
CASE total WHEN 1 THEN (JOIN gadgets ON gadgets.gadgetId = orders.gadgetId)

GROUP BY orders.orderId
ORDER BY orders.orderId DESC;

mysql总是给我一个错误,我无法通过互联网找到任何解决方案。

4

3 回答 3

2

只需在 Join 中添加一个简单条件,它就可以工作(当然你已经做了Left Join)。

SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
LEFT JOIN gadgets ON gadgets.gadgetId = orders.gadgetId
and total=1   --Simple Logic
GROUP BY orders.orderId
ORDER BY orders.orderId DESC;
于 2013-07-16T06:52:49.167 回答
2
SELECT
    g.*, o.* 
FROM 
    orders AS o
  JOIN 
    ( SELECT orderId
      FROM orderdetails 
      GROUP BY orderId
      HAVING COUNT(*) = 1
     ) AS od 
     ON o.orderId = od.orderId
  JOIN gadgets AS g
    ON g.gadgetId = o.gadgetId
ORDER BY 
    o.orderId DESC ;
于 2013-07-16T07:22:52.650 回答
0

您可以加入表格并获得仅具有的结果total = 1

SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
JOIN gadgets ON gadgets.gadgetId = orders.gadgetId
GROUP BY orders.orderId
HAVING total = 1
ORDER BY orders.orderId DESC;

高温高压

于 2013-07-16T07:02:21.850 回答