Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change mysql output based on value

Tags:

mysql

For example, if queue_watch shows a 0, I want the actual mysql output to say No, else say Yes. Changing the scheme is not an option.

SELECT user.user_name, queue.queue_name, queue_access.queue_access,
    queue_access.queue_watch
FROM queue_access
INNER JOIN user ON user.user_id = queue_access.user_id
INNER JOIN queue ON queue.queue_id = queue_access.queue_id
WHERE queue_access <> '' OR queue_watch = 1
ORDER BY user_name;

The SQL works for what I need, but I like to know if changing the output using SQL rather than PHP is possible. Also, is it possible to group all the queue_names in one row to each user_name so I don't have to have 153 rows returned.

Thanks

like image 477
Jonathan Weinraub Avatar asked May 22 '12 20:05

Jonathan Weinraub


People also ask

What is %s and %D in MySQL?

12 years, 10 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

How do I redirect output to a file in MySQL?

Save MySQL Results to a File There's a built-in MySQL output to file feature as part of the SELECT statement. We simply add the words INTO OUTFILE, followed by a filename, to the end of the SELECT statement. For example: SELECT id, first_name, last_name FROM customer INTO OUTFILE '/temp/myoutput.

How do I select a condition in MySQL?

You can specify any condition using the WHERE clause. You can specify more than one condition using the AND or the OR operators. A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.


2 Answers

It not an over head. It is better to be done in the query, I feel.

Try this -

SELECT user.user_name, queue.queue_name, queue_access.queue_access,
       IF(queue_access.queue_watch = 0, 'No', 'Yes')
FROM queue_access
INNER JOIN user ON user.user_id = queue_access.user_id
INNER JOIN queue ON queue.queue_id = queue_access.queue_id
WHERE queue_access <> '' OR queue_watch = 1
ORDER BY user_name;
like image 108
JHS Avatar answered Nov 13 '22 04:11

JHS


You can use the standard CASE expression. There are two slightly different ways to write a CASE expression.

Simple case expression:

SELECT
    CASE queue_access.queue_watch
        WHEN 0 THEN 'No'
        ELSE 'Yes'
    END AS your_alias,
    ...

Searched case expression:

SELECT
    CASE WHEN queue_access.queue_watch = 0 THEN 'No' ELSE 'Yes' END AS your_alias,
    ...

Or you could use the MySQL specific IF construct:

SELECT
    IF(queue_access.queue_watch, 'Yes', 'No') AS your_alias,
    ...

You may want to consider what should happen if your value is something other than 0 or 1.

like image 39
Mark Byers Avatar answered Nov 13 '22 04:11

Mark Byers