Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do this with MySQL?

Tags:

sql

mysql

I am using MySQL and have two database tables as follows:

Users

id   username
--------------
1    Bill
2    Steve

Objects

user_id   key   value
----------------------
1         A     X
1         B     Y
1         C     Z
2         A     S
2         C     T

What query is required to produce the following result?

username   A  B  C
-------------------
Bill       X  Y  Z
Steve      S     T

I have tried this with an INNER JOIN, but end up with 5 rows (one for each corresponding object row).

Any help much appreciated.

like image 681
gjb Avatar asked Dec 02 '11 21:12

gjb


People also ask

How do I query a MySQL database?

If you want to use PHP to query your MySQL database you can do that by either entering the MySQL query command in the PHP script or define the command as a variable and use the variable when needed.

How do I run a Preparedstatement in MySQL?

EXECUTE the PREPARED statementEXECUTE stmt USING @variable_name; Here @variable_name will have the value which we want tp pass at the place of ? in the PREPARE statement. We need to set the value of @variable_name by using SET statement before executing the prepared statement.

Is there a GUI for MySQL?

Database GUIs have been created in order to make it easy to manage MySQL databases visually, without having to manually type SQL commands. GUIs make the processes of designing, creating, and administering databases easier and more convenient.


1 Answers

If 'A', 'B', and 'C' are known beforehand, you can do this:

SELECT users.username,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'A'
       ) AS a,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'B'
       ) AS b,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'C'
       ) AS c
  FROM users
 ORDER
    BY users.username
;
like image 76
ruakh Avatar answered Sep 24 '22 08:09

ruakh