473,769 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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)?
Jul 17 '05 #1
11 2314
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 - http://www.electrictoolbox.com/
Jul 17 '05 #2
>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

Jul 17 '05 #3
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 - http://www.electrictoolbox.com/
Jul 17 '05 #4
go***********@b urditt.org (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.
Jul 17 '05 #5
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 - http://www.electrictoolbox.com/
Jul 17 '05 #6
Chris Hope <bl*******@elec trictoolbox.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.C ollegeID)
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, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 17 '05 #7
Tim Roberts wrote:
Chris Hope <bl*******@elec trictoolbox.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.C ollegeID)
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.C ollegeID
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 - http://www.electrictoolbox.com/
Jul 17 '05 #8
I noticed that Message-ID: <mv************ *************** *****@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 http://www.ckdog.co.uk/rfdmaker/
Jul 17 '05 #9
On Thu, 14 Oct 2004 14:49:03 +1300, Chris Hope
<bl*******@elec trictoolbox.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.
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
11929
by: Theodor Ramisch | last post by:
Hi there, I've got a simple table with an ID and a parentID field which build the relation between the entries. Now I want to select some entries and count their childs. This is what I tried: SELECT NAME, ID, parentID, (SELECT COUNT(ID) FROM myTable WHERE parentID=???ID???) AS CHILDS FROM myTable WHERE parentID=0 ORDER BY parentID ASC
3
7341
by: David | last post by:
Consider this SQL Query: ----------------------------------------------------------------- SELECT c.CASE_NBR, DATEDIFF(d, c.CREATE_DT, GETDATE()) AS Age, c.AFFD_RCVD, c.PRV_CRD_ISS, x.RegE, x.Type, x.Fraud, c.CUST_FN + ' ' + c.CUST_LN AS CustFullName, c.ATM_CKCD_NBR, x.TotalLoss, x.Queue, x.Status, c.QUEUE AS Expr1, x.CHECK_ACT_NBR, c.CUST_LN, c.SSN, c.CREATE_DT FROM ( SELECT TOP 9999999 cl.CASE_NBR, cl.SSN, cl.CREATE_DT,
4
2367
by: Wanny | last post by:
Hi There, I can't seem to see what's wrong with the query below DELETE FROM Users_Details UD1 WHERE UD1.UserID = ( SELECT TOP 1 UD2.UserID FROM Users_Details UD2 WHERE UD1.useremail = UD2.useremail
3
7807
by: krystoffff | last post by:
Hi I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the same query with a count(*) to know how many pages I will get (number total of rows/ X). The problem is my query is very slow (maybe 5s) because there is much
5
8215
by: Todd | last post by:
Data related to the query I'm working on is structured such that TableA and TableB are 1-many(optional). If an item on TableA has children on TableB, I need to use the Max(tstamp) from Table B in a condition, otherwise I need to use a tstamp from TableA (note:there are additional tables and conditions for this query, but this problem is based around these 2). I attempted having TableB (as B) "left outer joined" to TableA, and a condition...
7
1788
by: Patrick Fisher | last post by:
Hi I have a table which Contains entries with RefCode field containing INVP or INVPD Common fields in each entry would be InvoiceNo, Total and PurTyp for example. You could have 1001 500.50 INVP 1 1001 500.50 INVPID 1 1002 123.00 INVP 1
4
320
by: ungahz | last post by:
hi all. im having a problem and wondering if anyone an help. i have the following tables along with column names (too many columns so im just including the relevent ones): folders --------- name id categoryid
4
5959
by: Richard | last post by:
In a manufacturing document control situation, a procedure revision table named has principal columns and and satellite data columns , , . A unique index and to ensure each procedure name has only unique revision numbers. A form has a listbox for selecting a procedure and revision for browsing, and a checkbox 'Show all'. When ShowAll is true the listbox rowsource can be . When ShowAll is false the listbox should only show each...
0
1139
by: eltontodd | last post by:
I have a query that I need to run on a database that is on a SQL Server 7 installation. When I run the query on that database it takes forever. If I take the same query and run it on a database that is on a SQL Server 2000 installation it runs under a minute. I was wondering if someone might be able to help me redefine the query so that it works faster under SQL Server 7 but still returns the same results. The query is: Select DISTINCT...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.