Writing SQL query without subselect

Ask a Question related to PHP Development, Design and Development.

  1. #1

    Default Writing SQL query without subselect

    I'm stuck on a host that is still running MYSQL version 3.

    I need to flatten out a relationship to AND a set of criteria.

    In a nutshell

    User
    UserID
    UserEmail
    UserOther

    UserSkills
    UserID
    SkillCode

    Any user may have zero, one, or many UserSkills.

    I need to find a list of UserIDs for Users who have SkillCodes A and SkillCode
    B.

    How do I write the query (queries)?
    Steven Stern Guest

  2. Similar Questions and Discussions

    1. mySQL query writing problem
      I have a table with a dozen or so fields. I am trying to return all 12 fields in all records that contain an entry in the field named 'week'. This...
    2. Writing Query for data range does not output
      The cfoutput tag for this query does not display any data. SELECT Title, SVNo, RevNo, FileName, Type, ReleaseDate, Platform, PCNs,...
    3. I Need help writing a query
      I hope I give enough information for my delimma. I have an ACCESS database with 3 tables: -Client (clientid, name) -ClientClosedDates (clientid,...
    4. subselect argh!
      Why does subselect only work sometimes. I'm trying to scale a text path (without scaling the text). When I click on an object with the pointer,...
    5. Calling a Java SP with an embeded subselect crashes DB
      I've tested this on several PCs, all have the same issue. I create a Java SP (using the wizard or manually) with at least one parameter that is a...
  3. #2

    Default Re: Writing SQL query without subselect

    Steven Stern wrote:
    > I'm stuck on a host that is still running MYSQL version 3.
    Well even if you had a host with 4.0.x you still wouldn't be able to do
    subqueries. They won't be available until 4.1.x is released, and it's still
    in beta (or is it gamma now?) Even then I suspect not many hosts will start
    to host it until at least another couple of minor revisions have passed.
    > I need to flatten out a relationship to AND a set of criteria.
    >
    > In a nutshell
    >
    > User
    > UserID
    > UserEmail
    > UserOther
    >
    > UserSkills
    > UserID
    > SkillCode
    >
    > Any user may have zero, one, or many UserSkills.
    >
    > I need to find a list of UserIDs for Users who have SkillCodes A and
    > SkillCode B.
    >
    > How do I write the query (queries)?
    You need to join the table to itself (which is often more efficient than
    using a subquery anyway) along the lines of this:

    SELECT UserID
    FROM User u
    INNER JOIN UserSkills us1 ON u.UserID = us1.UserID
    INNER JOIN UserSkills us2 ON u.UserID = us2.UserID
    WHERE us1.SkillCode = 'A'
    AND us2.SkillCode = 'B'

    I have *not* tested this but it should work.

    --
    Chris Hope - The Electric Toolbox - [url]http://www.electrictoolbox.com/[/url]
    Chris Hope Guest

  4. #3

    Default Re: Writing SQL query without subselect

    >User
    > UserID
    > UserEmail
    > UserOther
    >
    >UserSkills
    > UserID
    > SkillCode
    >
    >Any user may have zero, one, or many UserSkills.
    >
    >I need to find a list of UserIDs for Users who have SkillCodes A and SkillCode
    >B.
    >
    >How do I write the query (queries)?
    Untested, but this should work.

    SELECT u.UserID
    FROM User u, UserSkills a, UserSkills b
    WHERE u.UserID = a.UserID and a.UserID = b.UserID and
    a.SkillCode = 'A' and b.SkillCode = 'B';

    This gets much messier when the number of skill codes is variable -
    you probably end up having PHP construct a query in a loop.

    Gordon L. Burditt

    Gordon Burditt Guest

  5. #4

    Default Re: Writing SQL query without subselect

    Gordon Burditt wrote:
    >>User
    >> UserID
    >> UserEmail
    >> UserOther
    >>
    >>UserSkills
    >> UserID
    >> SkillCode
    >>
    >>Any user may have zero, one, or many UserSkills.
    >>
    >>I need to find a list of UserIDs for Users who have SkillCodes A and
    >>SkillCode B.
    >>
    >>How do I write the query (queries)?
    >
    > Untested, but this should work.
    >
    > SELECT u.UserID
    > FROM User u, UserSkills a, UserSkills b
    > WHERE u.UserID = a.UserID and a.UserID = b.UserID and
    > a.SkillCode = 'A' and b.SkillCode = 'B';
    >
    > This gets much messier when the number of skill codes is variable -
    > you probably end up having PHP construct a query in a loop.
    This is essentially the same as the inner join query I posted. The only
    difference is I find the inner join type queries much easier to read
    because it's more clear where the relationships between the tables are.

    I used to always write my queries the way that Gordon has here but then
    started working for about a year at a Microsoft shop using SQL Server, and
    they had some great standards documents and always wrote their queries
    using inner joins. I found it a little odd to start with but then quickly
    adopted the style for all my database work because it makes more complex
    queries much easier to read.

    --
    Chris Hope - The Electric Toolbox - [url]http://www.electrictoolbox.com/[/url]
    Chris Hope Guest

  6. #5

    Default Re: Writing SQL query without subselect

    On Thu, 14 Oct 2004 09:48:41 +1300 (more or less), Chris Hope
    <blackhole@electrictoolbox.com> wrote:
    >Gordon Burditt wrote:
    >
    >>>User
    >>> UserID
    >>> UserEmail
    >>> UserOther
    >>>
    >>>UserSkills
    >>> UserID
    >>> SkillCode
    >>>
    >>>Any user may have zero, one, or many UserSkills.
    >>>
    >>>I need to find a list of UserIDs for Users who have SkillCodes A and
    >>>SkillCode B.
    >>>
    >>>How do I write the query (queries)?
    >>
    >> Untested, but this should work.
    >>
    >> SELECT u.UserID
    >> FROM User u, UserSkills a, UserSkills b
    >> WHERE u.UserID = a.UserID and a.UserID = b.UserID and
    >> a.SkillCode = 'A' and b.SkillCode = 'B';
    >>
    >> This gets much messier when the number of skill codes is variable -
    >> you probably end up having PHP construct a query in a loop.
    >
    >This is essentially the same as the inner join query I posted. The only
    >difference is I find the inner join type queries much easier to read
    >because it's more clear where the relationships between the tables are.
    >
    >I used to always write my queries the way that Gordon has here but then
    >started working for about a year at a Microsoft shop using SQL Server, and
    >they had some great standards documents and always wrote their queries
    >using inner joins. I found it a little odd to start with but then quickly
    >adopted the style for all my database work because it makes more complex
    >queries much easier to read.
    Thanks. I'm off to give it a shot.
    Steven Stern Guest

  7. #6

    Default Re: Writing SQL query without subselect

    On Thu, 14 Oct 2004 09:26:23 +1300 (more or less), Chris Hope
    <blackhole@electrictoolbox.com> wrote:
    >SELECT UserID
    >FROM User u
    >INNER JOIN UserSkills us1 ON u.UserID = us1.UserID
    >INNER JOIN UserSkills us2 ON u.UserID = us2.UserID
    >WHERE us1.SkillCode = 'A'
    >AND us2.SkillCode = 'B'
    BINGO!

    Here's a full-fledged working query

    SELECT DISTINCT
    mp.UserId,mp.LastName,FirstName,City,State,Email,R egularMember,AlumniMember,HomePhone,
    ShowResume, mp.SearchObjective, mp.BackgroundFunction, mp.BackgroundTitles,
    mp.BackgroundIndustries,mp.PreviousCompanies, mr.TagLine, mr.ExecSummary,
    mr.JobHistory, mr.Education, fj.comments, fj.NewTitle, fj.NewCompany,
    fj.NewIndustry, fj.comments FROM ((MemberProfile mp left join MemberResume mr
    on mp.UserId=mr.UserID) left join FoundJob fj on mp.UserId=fj.UserId) INNER
    JOIN fcodes fc0 ON mp.UserID = fc0.UserID INNER JOIN fcodes fc1 ON mp.UserID =
    fc1.UserID INNER JOIN fcodes fc2 ON mp.UserID = fc2.UserID INNER JOIN fcodes
    fc3 ON mp.UserID = fc3.UserID WHERE (fc0.fcode='A' AND fc1.fcode='B' AND
    fc2.fcode='C' AND fc3.fcode='E') ORDER BY mp.LastName,FirstName

    The inner joins are built by

    $cat_query_add_joins="";
    if ($cat != '') {
    $ccount=count($cat);
    $cat_query_add = "(";
    for ($i=0;$i<$ccount;$i++) {
    if ($i>0) $cat_query_add.=" AND ";
    $cat_query_add_joins.=" INNER JOIN fcodes fc$i ON mp.UserID =
    fc$i.UserID ";
    $cat_query_add.="fc$i.fcode='$cat[$i]'";
    }
    $cat_query_add.=")";
    }

    Steven Stern Guest

  8. #7

    Default Re: Writing SQL query without subselect

    [email]gordonb.peuhl@burditt.org[/email] (Gordon Burditt) wrote:

    [snip]
    >This gets much messier when the number of skill codes is variable -
    >you probably end up having PHP construct a query in a loop.
    select userid from userskills
    group by userid
    where skillcode in ('A','B','C','D')
    having count(*)=4

    The in has the list and the count is compared to the number of
    skills.

    If you want more user data,

    select <whatever> from user
    where userid in (<above query>)
    order by <whatever>

    Sincerely,

    Gene Wirchenko

    Computerese Irregular Verb Conjugation:
    I have preferences.
    You have biases.
    He/She has prejudices.
    Gene Wirchenko Guest

  9. #8

    Default Re: Writing SQL query without subselect

    Gene Wirchenko wrote:
    >>This gets much messier when the number of skill codes is variable -
    >>you probably end up having PHP construct a query in a loop.
    >
    > select userid from userskills
    > group by userid
    > where skillcode in ('A','B','C','D')
    > having count(*)=4
    Nice solution :)

    --
    Chris Hope - The Electric Toolbox - [url]http://www.electrictoolbox.com/[/url]
    Chris Hope Guest

  10. #9

    Default Re: Writing SQL query without subselect

    Chris Hope <blackhole@electrictoolbox.com> wrote:
    >
    >I used to always write my queries the way that Gordon has here but then
    >started working for about a year at a Microsoft shop using SQL Server, and
    >they had some great standards documents and always wrote their queries
    >using inner joins. I found it a little odd to start with but then quickly
    >adopted the style for all my database work because it makes more complex
    >queries much easier to read.
    Do you think so? Maybe you could post a good example that shows this.

    For me, most SQL reads like an English sentence. The INNER JOIN syntax
    disturbs that. Compare this:

    SELECT r.RID, r.LastName, p.FirstName, r.Address, r.City, r.State,
    u.CollegeName
    FROM
    ((registration r INNER JOIN person p ON r.RID = p.RID)
    INNER JOIN university u ON p.CollegeID=u.CollegeID)
    WHERE
    r.LastName = 'Smith';

    to this:

    SELECT r.RID, r.LastName, p.FirstName, r.Address, r.City, r.State,
    u.CollegeName
    FROM
    registration r,
    person p,
    university r
    WHERE r.RID = p.RID
    AND p.CollegeID = u.CollegeID
    AND r.LastName = 'Smith';

    For me, the second example reads more naturally. It gathers the list of
    affected tables into one easily identifiable place, and makes the
    connections part of the WHERE selection process. Query optimizers will
    make these exactly equivalent. It gets even worse as the number of tables
    increases.

    It's probably a personal preference thing.
    --
    - Tim Roberts, [email]timr@probo.com[/email]
    Providenza & Boekelheide, Inc.
    Tim Roberts Guest

  11. #10

    Default Re: Writing SQL query without subselect

    Tim Roberts wrote:
    > Chris Hope <blackhole@electrictoolbox.com> wrote:
    >>
    >>I used to always write my queries the way that Gordon has here but then
    >>started working for about a year at a Microsoft shop using SQL Server, and
    >>they had some great standards documents and always wrote their queries
    >>using inner joins. I found it a little odd to start with but then quickly
    >>adopted the style for all my database work because it makes more complex
    >>queries much easier to read.
    >
    > Do you think so? Maybe you could post a good example that shows this.
    >
    > For me, most SQL reads like an English sentence. The INNER JOIN syntax
    > disturbs that. Compare this:
    >
    > SELECT r.RID, r.LastName, p.FirstName, r.Address, r.City, r.State,
    > u.CollegeName
    > FROM
    > ((registration r INNER JOIN person p ON r.RID = p.RID)
    > INNER JOIN university u ON p.CollegeID=u.CollegeID)
    > WHERE
    > r.LastName = 'Smith';
    >
    > to this:
    >
    > SELECT r.RID, r.LastName, p.FirstName, r.Address, r.City, r.State,
    > u.CollegeName
    > FROM
    > registration r,
    > person p,
    > university r
    > WHERE r.RID = p.RID
    > AND p.CollegeID = u.CollegeID
    > AND r.LastName = 'Smith';
    >
    > For me, the second example reads more naturally. It gathers the list of
    > affected tables into one easily identifiable place, and makes the
    > connections part of the WHERE selection process. Query optimizers will
    > make these exactly equivalent. It gets even worse as the number of tables
    > increases.
    >
    > It's probably a personal preference thing.
    I would agree with it being a personal preference because when the database
    server optimises your query it's not going to make a difference either way,
    as they are fundamentally the same query.

    To me the inner join syntax is much more readable because to me it's more
    easy to see what you are joining them, than having to work it out from
    looking at the where clause.

    You don't actually need those braces around the from and inner join bits in
    your example, and I'd reformat it like so (which, to me, makes it a lot
    more readable):

    SELECT r.RID, r.LastName, p.FirstName, r.Address, r.City, r.State,
    u.CollegeName
    FROM registration r
    INNER JOIN person p ON r.RID = p.RID
    INNER JOIN university u ON p.CollegeID=u.CollegeID
    WHERE r.LastName = 'Smith';

    I cannot give you a better example than this as it simply reads better to
    me, whereas the non inner join syntax reads better to you :)

    --
    Chris Hope - The Electric Toolbox - [url]http://www.electrictoolbox.com/[/url]
    Chris Hope Guest

  12. #11

    Default Re: Writing SQL query without subselect

    I noticed that Message-ID: <mvbsm01gscp0qo57o3ftl3dpljffhtvt33@4ax.com>
    from Tim Roberts contained the following:
    >For me, the second example reads more naturally.
    I'm with you there.

    --
    Geoff Berrow (put thecat out to email)
    It's only Usenet, no one dies.
    My opinions, not the committee's, mine.
    Simple RFDs [url]http://www.ckdog.co.uk/rfdmaker/[/url]
    Geoff Berrow Guest

  13. #12

    Default Re: Writing SQL query without subselect

    On Thu, 14 Oct 2004 14:49:03 +1300, Chris Hope
    <blackhole@electrictoolbox.com> wrote:
    >Gene Wirchenko wrote:
    >
    >>>This gets much messier when the number of skill codes is variable -
    >>>you probably end up having PHP construct a query in a loop.
    >>
    >> select userid from userskills
    >> group by userid
    >> where skillcode in ('A','B','C','D')
    >> having count(*)=4
    >
    >Nice solution :)
    Minor syntax quibble: does MySQL allow "where" after "group by"?

    Lemming
    --
    Curiosity *may* have killed Schrodinger's cat.
    Lemming Guest

  14. #13

    Default Re: Writing SQL query without subselect

    On Thu, 14 Oct 2004 14:49:03 +1300, Chris Hope
    <blackhole@electrictoolbox.com> wrote:

    [Aargh! The amended fu got me. Reposting]
    >Gene Wirchenko wrote:
    >
    >>>This gets much messier when the number of skill codes is variable -
    >>>you probably end up having PHP construct a query in a loop.
    >>
    >> select userid from userskills
    >> group by userid
    >> where skillcode in ('A','B','C','D')
    >> having count(*)=4
    >
    >Nice solution :)
    Minor syntax quibble: does MySQL allow "where" after "group by"?

    Lemming
    --
    Curiosity *may* have killed Schrodinger's cat.
    Lemming Guest

  15. #14

    Default Re: Writing SQL query without subselect

    Lemming wrote:
    > On Thu, 14 Oct 2004 14:49:03 +1300, Chris Hope
    > <blackhole@electrictoolbox.com> wrote:
    >
    > [Aargh! The amended fu got me. Reposting]
    >
    >>Gene Wirchenko wrote:
    >>
    >>>>This gets much messier when the number of skill codes is variable -
    >>>>you probably end up having PHP construct a query in a loop.
    >>>
    >>> select userid from userskills
    >>> group by userid
    >>> where skillcode in ('A','B','C','D')
    >>> having count(*)=4
    >>
    >>Nice solution :)
    >
    > Minor syntax quibble: does MySQL allow "where" after "group by"?
    Looks like he got the query in the wrong order, because you are correct,
    group by must be after the where clause. Therefore his query should be:

    select userid from userskills
    where skillcode in ('A','B','C','D')
    group by userid
    having count(*)=4

    --
    Chris Hope - The Electric Toolbox - [url]http://www.electrictoolbox.com/[/url]
    Chris Hope Guest

  16. #15

    Default Re: Writing SQL query without subselect

    Chris Hope <blackhole@electrictoolbox.com> wrote:
    >Lemming wrote:
    [snip]
    >> Minor syntax quibble: does MySQL allow "where" after "group by"?
    >
    >Looks like he got the query in the wrong order, because you are correct,
    >group by must be after the where clause. Therefore his query should be:
    I beg the leniency of the court, Your Honour.

    In my dialect (Visual FoxPro), it does not matter. Now that I
    look at it, where then group then having makes sense from a
    chronological perspective.

    [snip]

    Sincerely,

    Gene Wirchenko

    Computerese Irregular Verb Conjugation:
    I have preferences.
    You have biases.
    He/She has prejudices.
    Gene Wirchenko Guest

  17. #16

    Default Re: Writing SQL query without subselect

    On Fri, 15 Oct 2004 14:07:51 +1300, Chris Hope
    <blackhole@electrictoolbox.com> wrote:
    >Looks like ...
    [snip]

    You keep changing the followup-to line and removing most of the
    groups. Please don't do that. I don't read comp.lang.php, so if I
    was to not change followup-to back to include the full list of groups
    I would be posting to groups I don't read, so wouldn't see either my
    own post nor any replies.

    Lemming
    --
    Curiosity *may* have killed Schrodinger's cat.
    Lemming Guest

Posting Permissions

  • You may not post new threads
  • You may post replies
  • You may not post attachments
  • You may not edit your posts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139