Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from same table, different rows, different columns

Tags:

mysql

My MySQL skills are very basic, so What I need (if possible) is a single SELECT statement that selects different columns from different rows in the same table. Most Google comes up with has to do with combining different tables or selecting same columns from different rows.

Table

id  |  c1  |  c2  |  c3  |  c4  |  c5  |  c6  |  c7  
-----------------------------------------------------   
1   | THIS | THIS | THIS |   a  |   a  |   a  |   a  
2   |   a  |   a  |   a  |   a  | THIS | THIS |   a     

I'd like to select columns c1, c2, c3 from row 1 and c5, c6 from row 2. Column names and id numbers are known.

I could fire two queries and combine the data:

   SELECT c1,c2,c3 FROM table WHERE id=1
   SELECT c5,c6 FROM table WHERE id=2

or I can fetch all the columns from the two rows simultaniously and filter out the data I need afterwards

   SELECT c1,c2,c3,c5,c6 FROM table WHERE id=1 OR id=2

My question: is there a SELECT statement that combines the two so I get the combined results in one query?

I found out UNION could work, but that only works if the number of columns selected is the same in both select-statements. And in this case, the aren't.

Any help would be appreciated.

[edit] See my answer below.

like image 324
Michel Avatar asked Sep 16 '26 08:09

Michel


1 Answers

The answers above still didn't do exactly what I wanted, because those queries returned two rows and/or messed with the column names.

In the end it turned out to be pretty simple:

SELECT * 
FROM (SELECT c1,c2,c3 FROM table WHERE id=1) AS t1,
FROM (SELECT c5,c6 FROM table WHERE id=2) AS t2

it returns one row, containing the values for c1, c2, c3, c5 and c6 with their corresponding column names

like image 190
Michel Avatar answered Sep 18 '26 23:09

Michel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!