I want to be able to select a custom list of fields with my queries without typing it all each time.
For example, I might want:
select A, A+B, (A div 2) / C, concat_ws(' ', A, B, C, D)
from my_table where blahblahblah
I'm going to replace blahblahblah with many different conditionals but is there a way to just type
select MY_CUSTOM
from my_table where A > 2 and G is not null;
select * from a view doesn't work since I still want to query based on fields I don't want to displayI don't really want to do a stored procedure.. where the syntax would be like
do_my_query('where A>2 and G is not null')
No, to answer your question straight, there are no macros in MySQL.
The closest thing is, as you know, a VIEW. But you would have to include in the view's select-list all the bare columns that you might want to write conditions on. Then just don't use SELECT * on the view; select only the columns you want.
CREATE VIEW my_table_enhanced AS
SELECT *, A+B AS expr1, (A DIV 2) / C AS expr2, CONCAT_WS(' ', A, B, C, D) AS expr3
FROM my_table;
Then
SELECT expr1, expr2, expr3
FROM my_table_enhanced
WHERE ...conditions...
It's usually bad practice to use SELECT * in production code anyway.
Not in the mysql command program itself, but there's nothing to stop you using (for example) the shell to provide that functionality, such as (in bash):
for name in Pax Bob ; do
echo "select * from people where name = '${name}'" | mysql ...
done
In your specific case, you could opt for a shell script smc that went something like this:
echo "select MY_CUSTOM from my_table $1" | mysql --user=x --password=y db
and call it with:
smc "where A>2 and G is not null"
although it may be prudent to add some debugging, and make sure access is granted only to those you trust not to try SQL injection attacks :-)
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