Jump to content


Photo

How to join 3 queries?[


  • Please log in to reply
2 replies to this topic

#1 tobifg

tobifg

    Newbie

  • New Members
  • Pip
  • 1 posts

Posted 07 July 2012 - 04:33 AM

Hi, I have columns

First name | last name | nr (individual number) | pref1 (preference1) | pref2 (preference2)| pref3(preference3) | situation | distance | sex


with 100 records in one table ap

 SELECT DISTINCT nr FROM ap 


First I have to display all records:

WHERE sex='F' and pref1='1' ORDER BY situation DESC, distance DESC
AND  WHERE (sex='F' and pref2='1' and situation= ' ' ) ORDER BY distance DESC
and WHERE (sex='F' and pref3='1' and situation= ' ' ) ORDER BY distance DESC
LIMIT 4

Then I would like to join results from:
WHERE sex='M' and pref1='1' ORDER BY situation DESC, distance DESC
AND WHERE (sex='M' and pref2='1' and situation= ' ' ) ORDER BY distance DESC
AND WHERE (sex='M' and pref3='1' and situation= ' ' ) ORDER BY distance DESC
LIMIT 7

and then join to all records from:

WHERE sex='F' and pref1='2' ORDER BY situation DESC, distance DESC
AND WHERE (sex='F' and pref2='2' and situation= ' ' ) ORDER BY distance DESC
AND WHERE (sex='F' and pref3='2' and situation= ' ' ) ORDER BY distance DESC
LIMIT 10

and so on...


In the results of all I can't have redundancies. It means when in first group of result I get individual number (column "nr") of '2112' it can't be displayed in last one of results.

Is it possible to do?

#2 btherl

btherl

    Advanced Member

  • Staff Alumni
  • 3,893 posts
  • LocationAustralia

Posted 07 July 2012 - 09:00 PM

If I understand you correctly, what you can do is this:

SELECT * FROM
  ( SELECT ... )
UNION ( SELECT ... )
UNION ( SELECT ... )

This will give you the unique results from all of the subqueries.

It depends what you mean by "join" though - usually a join in SQL means to match up results based on common data, such as "same name" or "same id number", and put the matching data in the same result row.  Your question sounds like you want to combine the result sets using "union", which basically means "Get these results, and these results, and these results, and return them all".
Your php questions answered at Flingbits

#3 vinny42

vinny42

    Advanced Member

  • Members
  • PipPipPip
  • 414 posts

Posted 12 August 2013 - 08:08 AM

Can you provide a small sample of data and an example output that you'd like to get from that data?  :happy-04:






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com