我的示例表:SELECT * FROM sample
+-----+-------+---------+
| id | fname | lname |
+-----+-------+---------+
| | | |
| 1 | Me | subject |
| 2 | I | subject |
| 3 | Myself| subject |
+-----+-------+---------+
是否可以在lname或任何公式上使用distinct进行此输出?
+-----+-------+---------+---------+---------+
| id | lname | fname | fname | fname |
+-----+-------+---------+---------+---------+
| | | | | |
| 1 |subject| me | I | Myself |
+-----+-------+---------+---------+---------+
感谢。
答案 0 :(得分:1)
不完全是你想要的但也许够了
select min(id) as id,
lname,
group_concat(fname separator ' ' order by id) as fname
from your_table
group by lname
答案 1 :(得分:0)
必须在语句中指定要返回这些列的列数和表达式。在您给出的示例中,是的,可以编写一个返回指定结果集的语句。
例如:
SELECT t.id
, t.lname
, ( SELECT f1.fname
FROM mytable f1
WHERE f1.lname = t.lname
ORDER BY f1.id
LIMIT 0,1
) AS fname
, ( SELECT f2.fname
FROM mytable f2
WHERE f2.lname = t.lname
ORDER BY f2.id
LIMIT 1,1
) AS fname
, ( SELECT f3.fname
FROM mytable f3
WHERE f3.lname = t.lname
ORDER BY f3.id
LIMIT 2,1
) AS fname
FROM ( SELECT MIN(m.id) AS id
, m.lname
FROM mytable m
GROUP BY m.lname
) t
在更一般的情况下,不可能改变单个SELECT
语句返回的列数。上面的示例可以扩展为返回fname
的四个,五个或更多值。但它的列数有限。