Can I automate the “on” statement from MySQL queries?
Pergunta
Background
In the process of QA/QC, I am writing lots of queries with multiple joins. I am using MySQL.
I would like to know how (if) I can simplify join statements, e.g. by setting default fields to join on.
My tables are named with a plural form of the object that they contain:
names
types
actions
surnames
names_surnames
where names_surnames
is a many-many lookup table
the primary keys are always id
and the foreign keys are always, e.g.
names.type_id
names.action_id
names_surnames.name_id
names_surnames.surname_id
My joins would be something like
select names.col1
from names join types on names.type_id = type.id
join actions on names.action_id = actions.id;
Question
Is there a way to get MySQL to always assume that tables will be joined with on thistables.thattable_id = thattable.id
?
Solução
How about creating views for joins that are used repeatedly ?
For example:
create view my_view as
select names.id as name_id, names.type_id, names.action_id, ...
from names join types on names.type_id = type.id
join actions on names.action_id = actions.id;
Outras dicas
If the columns were named the same in "both" tables, I think you could use NATURAL JOIN
. Although that won't work for you, your consistency in naming should still let you generate queries--or at least the join clauses--with a scripting language.
If the tables involved in the JOIN share identically named fields,
then you can use the USING clause of the JOIN syntax.
For example
IF the actions table had action_id as the primary key instead of id
and the types table had type_id as the primary key instead of id
THEN the query could be rewritten as
select names.col1
from names join types USING (type_id)
join actions USING (action_id);
Give it a Try !!!