假设我有一个order_dummy
表,其中存储了order_dummy_id, order_id, user_id, book_id, author_id
。你可能会抱怨我的桌子的逻辑,但我不知何故需要这样做。我想执行以下查询。
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 1
ORDER BY `order_dummy_id` DESC
LIMIT 1
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 2
ORDER BY `order_dummy_id` DESC
LIMIT 1
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 3
ORDER BY `order_dummy_id` DESC
LIMIT 1
请注意,一个订单中包含多个相同数量的书。因此,我通过降序列出order_dummy_id
并限制1
,因此只显示A BOOK的最新订单。但我的目标是在一张桌子上以这种方式展示其他书籍。我像这样使用了group by
......
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
GROUP BY book_id
但它只显示order_dummy_id
的升序结果。我不知道了。期待你的善意帮助!
答案 0 :(得分:1)
要一次性获取多个选择的结果,请使用UNION ALL:
(
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 1
ORDER BY `order_dummy_id` DESC
LIMIT 1
)
UNION ALL
(
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 2
ORDER BY `order_dummy_id` DESC
LIMIT 1
)
UNION ALL
(
SELECT *
FROM order_dummy
WHERE order_id = 1
AND user_id = 1
AND book_id = 3
ORDER BY `order_dummy_id` DESC
LIMIT 1
)
答案 1 :(得分:-1)
您需要normalize表格之间的关系。 book id不应该在订单行中,因为我们每个订单可以有多本书。您需要有一个名为“订购商品”的表格,并将您的图书与订购数量一起存储在那里 - 不需要多行。
要回答您的问题,我可以将您指向SQL运算符IN
:
select * from table where id in (1,2,3)
此外,根据上下文,您可以使用OR运算符
select * from table where id = 1 or id = 2 or id =3