Question

I have this problem,

Using a query as follows:

    mysql_query("SELECT * FROM mytable WHERE samefield='2' AND (SELECT
    COUNT(*) FROM mytableB as d WHERE d.samefield=samefield)");

returns me wrong results, the ideal that works is as follows:

    mysql_query("SELECT * FROM mytable WHERE samefield='2' AND (SELECT
    COUNT(*) FROM mytableB as d WHERE d.samefield=mytable.samefield)");

Notice how I had to explicitly enter the name of mytable for it to know the precise look up and get the correct results from the database, is there a definitive wild card to use as the outer most parent query to determine that d.samefield should equal to the very first parent without knowing it's alias, d.samefield=thewildcard.samefield is what I would be looking for, or somehow to specify that it should look up on its parent.

Because if I use d.samefield=samefield it just doesn't stick to the parent's value as it seems the problem is both having a field with the same name, query on table a and subquery on table b, the easiest if it worked were to have to declare always an alias on subqueries and let the first parent query fields be the ones for mysql to look up to, but it seems it does not work this way.

I know the whole question sounds kinda dumb but it is important to me as I've been around this for 3 hours now and tried methods such as a php function to send over the table name for which I want to append the subqueries into a main query and have even also tried php's eval but it all makes it very complicated solutions in the context for in which I need an answer for this.

Était-ce utile?

La solution

Why not put an alias on both tables?

SELECT a.* FROM mytable a WHERE a.samefield='2' AND
(SELECT COUNT(*) FROM mytableB b WHERE b.samefield=a.samefield);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top