我希望将两个专栏作为单一列加入...这是一个想法..
=======================================================
id | firstname | lastname
=======================================================
1 | Peter | Das
-------------------------------------------------------
2 | Das | James
-------------------------------------------------------
3 | vector | Call
______________________________________________________________
4 | cans | Das
sql查询应该看起来像这样(伪代码)
SELECT (lastname WHERE firstname='Das' AND firstname WHERE lastname='Das'
ORDER BY ID DESC) AS name
结果集看起来应该是这样的
======================
name
======================
cans
---------------------------------------
James
---------------------------------------
Peter
现在有人可以告诉我确切的查询是什么
欢迎每个想法提示建议
答案 0 :(得分:13)
SELECT CASE
WHEN firstname = 'Das' THEN lastname
ELSE firstname
END AS name
FROM table
WHERE firstname = 'Das'
OR lastname = 'Das'
ORDER BY id DESC
答案 1 :(得分:4)
看起来像是UNION
查询的作业
SELECT id, firstName AS name
FROM table
WHERE lastName = 'Das'
UNION ALL
SELECT id, lastName AS name
FROM table
WHERE firstName = 'Das'
ORDER BY id DESC
答案 2 :(得分:2)
你没有告诉我们你的桌子的名字。假设它被称为mynames
,这应该有效:
select case when firstname = 'Das' then lastname
else firstname end as name from mynames
where lastname = 'Das' or firstname = 'Das' order by id desc;
以下是MySQL编写的一些测试代码,用于验证解决方案的工作原理:
mysql> create table mynames(
-> id int unsigned primary key auto_increment,
-> firstname varchar(32) not null,
-> lastname varchar(32) not null
-> ) engine=innodb;
Query OK, 0 rows affected (0.45 sec)
mysql> insert into mynames (firstname, lastname) values
-> ('Peter', 'Das'),
-> ('Das', 'James'),
-> ('vector', 'Call'),
-> ('cans', 'Das');
Query OK, 4 rows affected (0.49 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from mynames;
+----+-----------+----------+
| id | firstname | lastname |
+----+-----------+----------+
| 1 | Peter | Das |
| 2 | Das | James |
| 3 | vector | Call |
| 4 | cans | Das |
+----+-----------+----------+
4 rows in set (0.00 sec)
mysql> select case when firstname = 'Das' then lastname
-> else firstname end as name from mynames
-> where lastname = 'Das' or firstname = 'Das' order by id desc;
+-------+
| name |
+-------+
| cans |
| James |
| Peter |
+-------+
3 rows in set (0.00 sec)