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.
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.
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.
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.
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
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With