-1

I have 2 tables joined by the membership.ID and memberDues.memberID. The membership table has a column, firstLast, which is unique for each row. If I have a value for firstLast, i should be able to then find the membership.ID and compare it to the memberDues.memberID. I am using the following query but it doesn't work:

SELECT * FROM memberDues, membership 
WHERE memberID = 
( SELECT ID FROM membership 
WHERE firstLast = 'Jim Smith') 
ORDER BY payDate DESC 
LIMIT 1

The result gets the correct memberDues.memberID and the other data from its row but pulls an unrelated data set from the membership table where even the ID is wrong. What's wrong with the query?

Drew
  • 24,851
  • 10
  • 43
  • 78
parboy
  • 67
  • 8
  • 2
    you are doing a cartesian product ... a cross join ... m rows and n rows yields m*n rows in resultset. Then you say, hey, just give me 1 row from the permutation of all – Drew Nov 03 '15 at 16:18
  • also, select * with joins tends to deliver some unwelcome columns. Fine for quick queries, but clean that up in production – Drew Nov 03 '15 at 16:26

3 Answers3

1

You can join the two tables on their shared ID values and then you can select only those rows which have firstLast = 'Jim Smith'. I think you can achieve more efficiently what you want (avoiding one additional select) using the following query:

SELECT aa.*, bb.*
FROM memberDues AS aa
INNER JOIN membership AS bb
ON aa.memberID = bb.ID
WHERE bb.firstLast = 'Jim Smith'
ORDER BY aa.payDate DESC
LIMIT 1;
Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37
0

You should use IN instead of equal sign:

SELECT * FROM memberDues, membership WHERE memberID IN
    (SELECT ID FROM membership WHERE firstLast = 'Jim Smith')
    ORDER BY payDate DESC LIMIT 1
kulaeff
  • 453
  • 3
  • 12
0

What's wrong with the query?

Your query joins 2 tables without specifying a condition to relate them.

For a fast start on your question, I'd try to specify membership.ID = memberDues.memberID in the where clause.

My personal advice is to use a LEFT JOIN using that condition in the ON clause. But it's more advanced SQL coding, and choices depends on the structure and the needs of this particular application.