How to create two column output from a single column

前提是你 提交于 2020-01-24 15:29:08

问题


I am guessing this is a noob question so please bear with me. I have a column in a mySQL table that contains both first name and last name plus other data (see table below).

fid | uid | value
 5  |  1  | John
 6  |  1  | Doe
 7  |  1  | some other data
 5  |  2  | Jane
 6  |  2  | Doe
 7  |  2  | some other data

What I would like to do is create a query where I split out the first and last names into their own columns for reporting purposes (like shown below).

First Name | Last Name
  John     |   Doe
  Jane     |   Doe

I haven't seen this question asked before here nor have I been able to Google (perhaps using the wrong keywords). I assume this is relatively simple but it is eluding me.

Thanks.


回答1:


You just need to join the table to itself with something like this:

select first_name.value, last_name.value
from your_table first_name
join your_table last_name on first_name.uid = last_name.uid
where first_name.fid = 5
  and last_name.fid  = 6

You can join a table to itself or join the same table multiple times as long as you use a different alias for each instance of the table.




回答2:


The self join isn't necessary:

  SELECT MAX(CASE WHEN yt.fid = 5 THEN yt.value ELSE NULL END) AS firstname,
         MAX(CASE WHEN yt.fid = 6 THEN yt.value ELSE NULL END) AS lastname
    FROM YOUR_TABLE yt
GROUP BY yt.uid



回答3:


You can do a self join on uid like so:

select 
  t1.value as 'First Name', 
  t2.value as 'Last Name' 
from 
  <table_name> t1 join 
  <table_name> t2 on t1.uid = t2.uid 
where 
  t1.fid = 5 and 
  t2.fid = 6;

To speed things up, and if it's not already there, consider adding an index on fid like so:

create index FID_IDX on <table_name> (fid);

this will prevent mysql from using a join buffer to resolve the query and it will go through the index instead.

However, the index will slow down your inserts and updates on this table a bit. If write performance is more important than read then do not add it.



来源:https://stackoverflow.com/questions/9345737/how-to-create-two-column-output-from-a-single-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!