Php 如何在同一查询中同时选择相似的值?
我的数据库如下所示,我需要从下表中获取单独列表中的所有0和1,也就是说,将所有的0放在一列中,将所有的1放在单独的列中 数据库Php 如何在同一查询中同时选择相似的值?,php,mysql,Php,Mysql,我的数据库如下所示,我需要从下表中获取单独列表中的所有0和1,也就是说,将所有的0放在一列中,将所有的1放在单独的列中 数据库 | id | value | ------------- | 1 | 0 | | 2 | 1 | | 3 | 0 | | 4 | 1 | 预期结果 | sp.id | stop | st.id | start| ------------------------------- | 1 | 0 | 2 |
| id | value |
-------------
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
预期结果
| sp.id | stop | st.id | start|
-------------------------------
| 1 | 0 | 2 | 1 |
| 3 | 0 | 4 | 1 |
或
对于预期结果1,您可以使用
case
select case when value=0 then id end as spid,
case when value=0 then value end as stop,
case when value=1 then id end as stid,
case when value=1 then value end as start
from yourtable.
但对于空行,您将得到NULL
,如下所示。如果可以,您可以使用上面的查询。如果是字符串
,则可以使用MAX()
或MIN()
和分组依据
来避免此空值
输出
+------+------+------+-------+
| spid | stop | stid | start |
+------+------+------+-------+
| 1 | 0 | | |
+------+------+------+-------+
| | | 2 | 1 |
+------+------+------+-------+
| 3 | 0 | | |
+------+------+------+-------+
| | | 4 | 1 |
+------+------+------+-------+
+----+-------+
| id | value |
+----+-------+
| 1 | 0 |
+----+-------+
| 3 | 0 |
+----+-------+
| 2 | 1 |
+----+-------+
| 4 | 1 |
+----+-------+
对于预期的输出2,可以直接使用UNION ALL
select id,value from test where value=0
union all
select id,value from test where value=1
输出
+------+------+------+-------+
| spid | stop | stid | start |
+------+------+------+-------+
| 1 | 0 | | |
+------+------+------+-------+
| | | 2 | 1 |
+------+------+------+-------+
| 3 | 0 | | |
+------+------+------+-------+
| | | 4 | 1 |
+------+------+------+-------+
+----+-------+
| id | value |
+----+-------+
| 1 | 0 |
+----+-------+
| 3 | 0 |
+----+-------+
| 2 | 1 |
+----+-------+
| 4 | 1 |
+----+-------+