I've got a query which is failing with an ambiguous column error. Unfortunately, because of the framework I'm using (Magento 1), I can't just resolve this problem by prefixing the column name with the correct table name in the 'where' clause.
Given the two example tables
T1 = colA | colB | colC
T2 = colD | colB | colE
I want a query that will join the tables on colA and colD, select only colC and colE, but have a where clause on T1's colB. The straight forward SQL would look like:
SELECT colC, colE
FROM T1 LEFT JOIN T2 ON colA=colD
WHERE T1.colB=1
The problem is that the 'where' clause is already set by core code as WHERE colB=1 and I can't easily change it to add the T1 prefix.
I've tried rewriting it as a sub query like this:
SELECT colC,colE
FROM T1 LEFT JOIN (SELECT colD,colE FROM T2) ON colA=colD
WHERE colB=1
This works and gives me what I'd expect, but its unacceptable slow.
Are there any clever SQL tricks that can be used to either optimise the subquery, or rewrite the join so I can use the where clause without the table prefix.
where colB =1be placed anywhere or does it has to end with it? Do you have a 1:1 relationship between your tables or cancolA=colDget you several rows in T2 for a row in T1? Do you by any chance use mysql 5.7? - Solarflare