简体   繁体   English

从mySQL中的单个表行中选择两行

[英]Selecting two rows from a single table row in mySQL

I have a table A (Id1, Id2, someValue) 我有一张表A (Id1, Id2, someValue)

What I want to achieve in mySQL: 我想在mySQL中实现的目标:

My SELECT query should return two rows: 我的SELECT查询应该返回两行:

Id1, someValue
Id2, someValue

(based on a certain condition - for example, where someValue > N) (基于某种条件 - 例如,someValue> N)

How can I achieve this without using UNION ? 如何在不使用UNION情况下实现这一目标?

Since this is not possible without using UNION , here is how to archive this with it: 由于这不可能不使用UNION ,以下是如何使用它进行存档:

(SELECT ID1 as ID, someValue FROM A WHERE someValue > N)
UNION
(SELECT ID2 as ID, someValue FROM A WHERE someValue > N)

How about: 怎么样:

SELECT 
    CASE
        WHEN somecondition THEN ID1
        ELSE ID2
    END AS ID, someValue
FROM that_table

The somecondition can be an expression similar to those that you use in a WHERE clause. somecondition可以是一个类似于WHERE子句中使用的表达式。

Could you not just use an or? 你能不能只使用或? for example: 例如:

select * from A where someValue = 'x' OR someValue 'y'

If you need the return in separated rows you'd better split the db schema to "id, someValue". 如果需要以分隔的行返回,则最好将db模式拆分为“id,someValue”。 On insert, just insert {id1_value, someValue}, {id2_value, someValue}, and on retrieve just select from table where value = someValue. 在插入时,只需插入{id1_value,someValue},{id2_value,someValue},并在检索时从表中选择value = someValue。 You'll get the return you expect. 你会得到你期望的回报。

If you need to relate id1 and id2 in some way (make a linked list or whatever), you may add the related id to the entry. 如果您需要以某种方式关联id1和id2(创建链接列表或其他),您可以将相关的id添加到条目中。 The schema could be {id, value, related_id}. 架构可以是{id,value,related_id}。

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

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