简体   繁体   English

选择表中具有相同表中不同列的值的条件的行

[英]Select rows in table with condition of value of different column in same table

I have got table which represent items in orders with columns like this: 我有一个表,它代表订单中的项目,像这样的列:

--------------------------------------------------
| id     |  item_id   |   item_name  |  order_id  |
--------------------------------------------------
| 1      |  12345     |   abcd       |  1001      |
--------------------------------------------------
| 2      |  55555     |   bbbb       |  1001      |
--------------------------------------------------
| 3      |  66666     |   cccc       |  1001      |
--------------------------------------------------
| 4      |  12345     |   abcd       |  1002      |
--------------------------------------------------
| 5      |  99999     |   yyyy       |  1002      |
--------------------------------------------------
| 6      |  12345     |   abcd       |  1003      |
--------------------------------------------------
| 7      |  98765     |   qqgg       |  1004      |
--------------------------------------------------
| 8      |  55112     |   ffdd       |  1004      |

I have an item with item_id = 12345 which is in several orders. 我有一个item_id = 12345的商品,有几个订单。

I would like to select all items, which fulfilled condition: 我想选择所有满足条件的项目:

  • items are in same orders like item_id = 12345 项目的顺序相同,例如item_id = 12345

I try this SQL command but I think my approach is bad. 我尝试使用此SQL命令,但我认为我的方法不好。

SELECT item_name   
FROM item_order
WHERE order_id IN (
      SELECT order_id 
      FROM item_order
      WHERE item_id = 12345
)

Result, what I would like to get is: 结果,我想得到的是:

--------------------------------------------------
| id     |  item_id   |   item_name  |  order_id  |
--------------------------------------------------
| 2      |  55555     |   bbbb       |  1001      |
--------------------------------------------------
| 3      |  66666     |   cccc       |  1001      |
--------------------------------------------------
| 5      |  99999     |   yyyy       |  1002      |
--------------------------------------------------

Thanks for advice and sorry if the topic is confused. 感谢您的建议,对于本主题感到困惑的情况,我们深感抱歉。

Seems like you're just missing another part of your condition: 似乎您只是缺少另一部分状况:

SELECT item_name   
FROM   item_order
WHERE   order_id IN (
        SELECT order_id 
        FROM item_order
        WHERE item_id = 12345
)
AND     item_id != 12345

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM