So I apologize if this has come up before, but I couldn’t find a solid answer.
I am trying to get a single column of ids from a set of 3 columns in my table joined with another table.
The select statement just to get a single column would be like this:
SELECT id FROM TableA JOIN TableB USING (key1, key2) WHERE someValue = X;
Now as I understand it I can do unions to get these like so:
SELECT spec_id1 AS id FROM TableA JOIN TableB USING (key1, key2) WHERE someValue1 = X
UNION
SELECT spec_id2 AS id FROM TableA JOIN TableB USING (key1, key2) WHERE someValue2 = Y
UNION
SELECT spec_id3 AS id FROM TableA JOIN TableB USING (key1, key2) WHERE someValue3 = Z
Is there a way to reuse the TableA JOIN TableB USING (key1, key2) so it isn’t joined for each select? I also have a WHERE condition that applies to all of the selects that is not shown above. Could I possibly reuse something like:
FROM TableA JOIN TableB USING (key1, key2) WHERE someOtherValue = W
I am trying to do this in PHP using mysqli. My original instinct was to use a temp table and query that, but I’m not sure how to handle that in mysqli. If I can use the table for multiple following queries that would be doubly ideal as there is extra data in the joined tables that could be used later.
Sorry if this is naive, but I’m not really a big web developer. Thanks in advance.
EDIT:
I am looking into temporary tables, and it seems like that might be a good way around it. I’d still like some confirmation on whether that’s a good idea or not before doing anything with it.
There is no shortcut – not without changing the tables’ design. Your approach is solid and you should not worry about having 3 joins in your query.
If the 3 lists of spec_ids are known to not have any overlapping values, then you could improve performance by changing
UNIONtoUNION ALL.One possible rewriting, without changing the overall
UNIONplan, is to change joins toEXISTSsubqueries:or – if the
spec_idsare all included in anotherBaseTable– you can have something like this which might yield a better execution plan: