ok I do have this table
| id | first | last | type
1 mp de bill
1 mark ve ship
2 dw her bill
2 dwi rra ship
now I want it to be like this
| id | bill.first | bill.last | ship.first | ship.last
1 mp de mark ve
2 dw her dwi rra
the main key of joining rows is by their ID is this possible?
I tried already using group by but I don't have an idea how to use it
and I don't know what word to use in google to search for the solution to my problem
I have only one table
Something like this should work -
select
t1.first,
t1.last,
t2.first,
t2.last,
t1.type
from
test t1
inner join test t2
on t1.id = t2.id
and t1.type = 'bill'
and t1.type != t2.type
Effectively, all you need is to perform an inner join on the same table
Try something like
select bill.id, bill.first, bill.last, ship.first, ship.last
from t as bill, t as ship
where bill.id = ship.id
and bill.type = 'bill'
and ship.type = 'ship'
Or you could use a Join to be more contemporary.
SELECT b.id, b.first, b.last, s.first, s.last
FROM bill b
LEFT JOIN ship s ON b.id=s.id AND b.type='bill' AND s.type='ship'
try this:
SELECT A.id,A.first, A.last,
B.first, B.last
FROM T2 A
INNER JOIN T2 B
ON A.id = B.id
AND A.type = 'bill'
AND B.type = 'ship'
You can do this with group by
and conditional aggregation:
select id,
max(case when type = 'bill' then first end) as "bill.first",
max(case when type = 'bill' then last end) as "bill.last",
max(case when type = 'ship' then first end) as "ship.first",
max(case when type = 'ship' then last end) as "ship.last"
from table t
group by id;
For your case, this produces exactly the same results as the join
. However, if you have multiple rows for a given value, then this will still generate only one row per id. Using max()
it will give one value from one of the rows. Using group_concat()
it would give all the values.
One advantage of this approach is that it will include all ids, even when some ids are missing "bill" records and others are missing "ship" records. Unfortunately, MySQL doesn't support full outer join
, so that situation is more difficult to handle using join
s.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.