Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在同一查询中同时选择相似的值?_Php_Mysql - Fatal编程技术网

Php 如何在同一查询中同时选择相似的值?

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 |

我的数据库如下所示,我需要从下表中获取单独列表中的所有0和1,也就是说,将所有的0放在一列中,将所有的1放在单独的列中

数据库

| 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     |
+----+-------+