Store a subquery in a variable

0

I am trying to store a subquery in a variable and then enter it in another query. The code I have is this:

$anu = "(SELECT DISTINCT Prod_Anun FROM productos where Prod_Anun = 'Particular')";

$consulta="SELECT * 
           FROM productos
           WHERE Prod_Tit LIKE '%$bus%'
           AND Prod_Anun = '$anu'";

Next I make the connection with the BDD and the whole process of showing the data by screen which does not work because I suppose that the method of passing the subquery is incorrect.

Thanks in advance

    
asked by gmarsi 23.03.2017 в 21:21
source

1 answer

1

What you are doing in good accounts is

$consulta="SELECT * 
           FROM productos
           WHERE Prod_Tit LIKE '%$bus%'
           AND Prod_Anun = '(SELECT DISTINCT Prod_Anun FROM productos where Prod_Anun = 'Particular')'";

And that syntactically does not make any sense. What you really want to do is

$consulta="SELECT * 
           FROM productos
           WHERE Prod_Tit LIKE '%$bus%'
           AND Prod_Anun IN (SELECT DISTINCT Prod_Anun FROM productos where Prod_Anun = 'Particular')";

But since the SELECT DISTINCT is a subset of the SELECT, in reality what you really-really want to do is

$consulta="SELECT * 
           FROM productos
           WHERE Prod_Tit LIKE '%$bus%'
           AND Prod_Anun IN (SELECT Prod_Anun FROM productos where Prod_Anun = 'Particular')";
    
answered by 23.03.2017 в 21:27