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:
SELECT A1.value as cable_length
, A2.value as drawing
, A3.value as optional
, A4.value as output_type
, A5.value as pressure_range
, A6.value as pressure_type
, A7.value as series
, A7.value as termination
FROM A1, A2, A3, A4, A5, A6, A7, A8
WHERE A1.ID = %s
AND A2.ID = %s
AND A3.ID = %s
AND A4.ID = %s
AND A5.ID = %s
AND A6.ID = %s
AND A7.ID = %s
AND A8.ID = %s
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.
SELECT A1.value as cable_length
, A2.value as drawing
, A3.value as optional
, A4.value as output_type
, A5.value as pressure_range
, A6.value as pressure_type
, A7.value as series
, A7.value as termination
FROM A1
LEFT JOIN A2
ON A2.ID = %s
LEFT JOIN A3
ON A3.ID = %s
LEFT JOIN A4
ON A4.ID = %s
LEFT JOIN A5
ON A5.ID = %s
LEFT JOIN A6
ON A6.ID = %s
LEFT JOIN A7
ON A7.ID = %s
LEFT JOIN A8
ON A8.ID = %s
WHERE A1.ID = %s
If none of the values are guaranteed present, the hack is to have a subquery that is a UNION ALL
of 8 queries that return the 8 columns with only one filled, then select the MAX
of 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.