I am trying to make an SQL statement that takes eight different numbers and searches eight different tables from one database for the corresponding value. I keep getting invalid syntax, but I can’t figure out why. Here is my code:
SELECT cable_length.ID, drawing.ID, optional.ID, output_type.ID, pressure_range.ID, pressure_type.ID, series.ID, termination.ID
FROM
(
SELECT value AS cable_length FROM A1 WHERE A1.id = %s
JOIN SELECT value AS drawing FROM A2 WHERE A2.id = %s,
JOIN SELECT value AS optional FROM A3 WHERE A3.id = %s,
JOIN SELECT value AS output_type FROM A4 WHERE A4.id = %s,
JOIN SELECT value AS pressure_range FROM A5 WHERE A5.id = %s,
JOIN SELECT value AS pressure_type FROM A6 WHERE A6.id = %s,
JOIN SELECT value AS series FROM A7 WHERE A7.id = %s,
JOIN SELECT value AS termination FROM A8 WHERE A8.id = %s
);
The %s will be changed to numbers only. The column name in each table is “ID” and “Value”. I want to search by “ID” and return “Value”. The table names are cable_length, etc. Any help is greatly appreciated.
If you know that all 8 values are present, you can join like this:
If you do not know this, but you’re guaranteed that the first value is present, then your query has to get uglier because you need left joins.
If none of the values are guaranteed present, the hack is to have a subquery that is a
UNION ALLof 8 queries that return the 8 columns with only one filled, then select theMAXof each column as that column name.This is an awful trick that I’ve used in the past to avoid performance problems with many left joins that only occasionally join.
Incidentally 8 tables named A1..A8 suggests that you need someone who is experienced with databases to look over your design and give you a much better layout.