0

I have a MySQL table named "proposition" with the primary key "idProposition" and an other table named "needs" with columns "idProposition" and "idRequirement". I'd want to get the propositions which linked requirements are all in the $requireList php array.

I tried to do like that:

$req = "SELECT idProposition FROM proposition
        WHERE (SELECT idProposition FROM proposition
                 WHERE needs.idProposition = proposition.idProposition
                       AND idRequirement NOT IN($requireList))
          IS NULL";

But when I make the request, I have the following error:

#1242 - Subquery returns more than 1 row 

Meaning that it can't test if the result (propositions having needs not in $requireList) is null because there are several results. How could I test if the internal SELECT provides result?

Thanks for you help.

2
  • why not just LIMIT 1?, or use JOINS.
    – user1897253
    Jan 15, 2015 at 17:24
  • There is no table needs in the FROM clauses of your query.
    – axiac
    Jan 15, 2015 at 17:35

2 Answers 2

0

Try this:

SELECT p.*
FROM proposition p
  INNER JOIN needs n ON n.idProposition = p.idProposition
WHERE idRequirement IN (1, 7, 9)    # blah, blah, blah, put your list here
GROUP BY p.idProposition
HAVING COUNT(idRequirement) = 3     # put the size of the list here

What it does: it SELECTs all the propositions together that are liked with requirements from the list. It doesn't matter if only one requirement is linked or all of them. Then it GROUPs those rows BY propositions. Each proposition will produce a single row of data. Then it keeps from these rows only those HAVING the same number of requirements as the size of your list (i.e. all the requirements are present).

I didn't test it but it should work. If it doesn't, just add COUNT(idRequirement) to the SELECT clause.

2
  • Doesn't work because for example, a proposition without requirement won't be detected whereas all its requirements are in the list.
    – yopla
    Jan 15, 2015 at 18:30
  • I found a quite dirty but working solution based on yours: I added in the data base the requirement 0 for all the propositions. $requireList never contains 0. And I used "HAVING COUNT(idRequirement)=1" so that only the unreachable condition remain.
    – yopla
    Jan 15, 2015 at 18:40
0

Try using

SELECT idProposition FROM proposition 
INNER JOIN needs on proposition.idProposition = needs.idproposition

instead of

SELECT idProposition FROM proposition
        WHERE (SELECT idProposition FROM proposition
                 WHERE needs.idProposition = proposition.idProposition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.