我有这样的查询:
SELECT i.*
FROM items i
WHERE i.id
IN (
SELECT c.item_id
FROM cart c
WHERE c.sessID=MY_SESSION_ID
)
它的工作非常漂亮,但我需要按购买日期(cart.id)DESC对购物车中的商品进行分类。 我不想在PHP中排序。我如何按cart.id排序?
我试过了:
SELECT i.*
FROM items i
WHERE i.id
IN (
SELECT c.item_id
FROM cart c
WHERE c.sessID=MY_SESSION_ID
)
ORDER BY c.id
但它没有正确排序。
答案 0 :(得分:2)
将子查询更改为Inner Join
。 Sub query
不允许您引用sub query
之外的列。所以将其更改为Inner join
SELECT i.*
FROM items i
JOIN (SELECT item_id,
id
FROM cart) C
ON i.id = c.item_id
AND c.sessID = MY_SESSION_ID
ORDER BY c.id Desc
或使用此。
SELECT i.*
FROM items i
JOIN cart C
ON i.id = c.item_id
AND c.sessID = MY_SESSION_ID
ORDER BY c.id Desc
答案 1 :(得分:1)
试试这个:
SELECT i.*
FROM items i
INNER JOIN cart c ON i.id = c.item_id
WHERE c.sessID = MY_SESSION_ID
GROUP BY i.id
ORDER BY MAX(c.id) DESC;
或强>
SELECT i.*
FROM items i
INNER JOIN (SELECT item_id, MAX(id) AS cid
FROM cart
WHERE sessID = MY_SESSION_ID
GROUP BY item_id
) AS c ON i.id = c.item_id
ORDER BY c.cid DESC;
答案 2 :(得分:1)
尝试此查询:
SELECT i.* FROM items i LEFT OUTER JOIN cart c
ON i.id = c.item_id WHERE c.sessID=MY_SESSION_ID AND
c.item_id is not null ORDER BY c.id