MySQL table -> Can you return the same row multiple times, in the same query?

佐手、 提交于 2019-12-17 09:57:04

问题


SELECT * FROM menu WHERE item_id = 1 OR item_id = 2 OR item_id = 3;

The above statement returns 3 rows. But the statement below only returns 2 rows.

SELECT * FROM menu WHERE item_id = 1 OR item_id = 1 OR item_id = 2;

And I understand why like, but is there a way to force item_id 1 to be returned twice???

Example of what I want to be returned:

id -> 1 Chips €2.50
id -> 1 Chips €2.50
id -> 2 Coke €1.60
--------------------
Total €6.60


回答1:


You could join on another table, for example

SELECT * FROM menu
INNER JOIN order_items ON menu.item_id = order_items.item_id
WHERE order_id = 123;

Or just duplicate them in your application.

You shouldn't really need to do what you're asking for.




回答2:


You would have to do something like this:

SELECT * FROM menu WHERE item_id = 1
UNION ALL
SELECT * FROM menu WHERE item_id = 1
UNION ALL
SELECT * FROM menu WHERE item_id = 2



回答3:


You just make a join among its aliases, e.g.

select top 5 * from item a, item b where a.itemid =1

It will print data like the following.

1 abc
1 abc
1 abc
1 abc
1 abc

Hope, you will understand.




回答4:


You need a way to generate a dummy rowset to do this, and MySQL lacks it.

You can do the following:

SELECT  *
FROM    (
        SELECT  1 AS x
        UNION ALL
        SELECT  1 AS x
        UNION ALL
        SELECT  2 AS x
        ) dummy
JOIN    menu
ON      menu.id = dummy.x



回答5:


Use unions:

SELECT * FROM menu WHERE item_id = 1
  UNION ALL
SELECT * FROM menu WHERE item_id = 1
  UNION ALL
SELECT * FROM menu WHERE item_id = 2



回答6:


why do you want to query db twice for same thing. Just query once and do the modification (add rows or display same row twice) using programming language you are using.

Something like

id -> 1 Chips €2.50 X 2
id -> 2 Coke €1.60
--------------------
Total €6.60



回答7:


The first answer looks wrong. It should be left outer join with order_items as first table...

SELECT * FROM order_items oi
left outer JOIN menu m
ON oi.item_id = m.item_id
WHERE order_id = 123;


来源:https://stackoverflow.com/questions/1109113/mysql-table-can-you-return-the-same-row-multiple-times-in-the-same-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!