The scenario:
two tables
CustomerTable
---------------
CustomerID
OrderID
CustomerName
CustomerEmail
CustomerPhone
OrderTable
---------------
OrderID
ProductID
ProductName
ProductCost
This database was handed to me and I was asked to solve a problem - it looks
like an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14).
I'm looking to get a list of all the customers who have ordered product #1,
UNLESS they've ordered product #14 in which case I don't want to know about
that customer at all.
Any help would be greatly appreciated! I'll watch the newsgroup for the
answer - hopefully your response can help someone else too. However, if you
prefer to email me directly, you can send it to me at bunchah at yahoo dot
com.
Thanks in advance!
(if it'll help, I'll buy the person offering the correct solution a beer -
pending age verification of course) ;)
-Al 11 2911
On Sat, 22 Nov 2003 00:52:35 GMT, "news-east.earthlink. net"
<ab************ ******@yahoo.no spam.com> wrote: The scenario:
two tables
CustomerTabl e --------------- CustomerID OrderID CustomerName CustomerEmai l CustomerPhon e
OrderTable --------------- OrderID ProductID ProductName ProductCost
This database was handed to me and I was asked to solve a problem - it looks like an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14). I'm looking to get a list of all the customers who have ordered product #1, UNLESS they've ordered product #14 in which case I don't want to know about that customer at all.
A literal translation could be:
SELECT DISTINCT CustomerID
FROM CustomerTable
WHERE CustomerID IN (SELECT CustomerID
FROM OrderTable
WHERE ProductID = 1)
AND CustomerID NOT IN (SELECT CustomerID
FROM OrderTable
WHERE ProductID = 14)
Or:
SELECT CustomerID
FROM CustomerTable
INNER JOIN OrderTable USING (OrderID)
WHERE ProductID = 1
MINUS
SELECT CustomerID
FROM CustomerTable
INNER JOIN OrderTable USING (OrderID)
WHERE ProductID = 14
--
Andy Hassall (an**@andyh.co. uk) icq(5747695) ( http://www.andyh.co.uk)
Space: disk usage analysis tool ( http://www.andyhsoftware.co.uk/space)
select ct.customerid
from CustomerTable ct
join OrderTable ot
on ct.orderid = ot.orderid
group by ct.customerid
having (count(case ot.productid when 1 then 1 else null end) > 0)
and (count(case ot.productid when 14 then 1 else null end) = 0)
order by ct.customerid
HTH,
Dave
"news-east.earthlink. net" <ab************ ******@yahoo.no spam.com> wrote in
message news:nr******** **********@news read2.news.atl. earthlink.net.. . The scenario:
two tables
CustomerTable --------------- CustomerID OrderID CustomerName CustomerEmail CustomerPhone
OrderTable --------------- OrderID ProductID ProductName ProductCost
This database was handed to me and I was asked to solve a problem - it
looks like an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14). I'm looking to get a list of all the customers who have ordered product
#1, UNLESS they've ordered product #14 in which case I don't want to know
about that customer at all.
Any help would be greatly appreciated! I'll watch the newsgroup for the answer - hopefully your response can help someone else too. However, if
you prefer to email me directly, you can send it to me at bunchah at yahoo dot com.
Thanks in advance!
(if it'll help, I'll buy the person offering the correct solution a beer - pending age verification of course) ;)
-Al
"Andy Hassall" <an**@andyh.co. uk> wrote in message
news:t5******** *************** *********@4ax.c om... On Sat, 22 Nov 2003 00:52:35 GMT, "news-east.earthlink. net" <ab************ ******@yahoo.no spam.com> wrote:
The scenario:
two tables
CustomerTabl e --------------- CustomerID OrderID CustomerName CustomerEmai l CustomerPhon e
OrderTable --------------- OrderID ProductID ProductName ProductCost
This database was handed to me and I was asked to solve a problem - it
lookslike an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14). I'm looking to get a list of all the customers who have ordered product
#1,UNLESS they've ordered product #14 in which case I don't want to know
aboutthat customer at all. A literal translation could be:
SELECT DISTINCT CustomerID FROM CustomerTable WHERE CustomerID IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 1) AND CustomerID NOT IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 14)
Or:
SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 1 MINUS SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 14
Andy, I don't think the second solution will work. First of all, MINUS is
not supported on SQL Server. Second, even if this is run on Oracle, the two
result sets you're performing the minus on are the joined tables, not the
single table CustomerTable. So the two sets are disjoint because ProductID
cannot be 1 and 14 simultaneously. So you'll end up with all the customers
who have ordered product #1, regardless of whether they have ordered product
#14 or not.
Since there's a beer involved here, I have to be a bit particular... ;-)
- Dave -- Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk) Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
"Dave Hau" <nospam_dave_no spam_123@nospam _netscape_nospa m.net_nospam> wrote
in message news:r%******** ***********@new ssvr27.news.pro digy.com... "Andy Hassall" <an**@andyh.co. uk> wrote in message news:t5******** *************** *********@4ax.c om... On Sat, 22 Nov 2003 00:52:35 GMT, "news-east.earthlink. net" <ab************ ******@yahoo.no spam.com> wrote:
The scenario:
two tables
CustomerTabl e --------------- CustomerID OrderID CustomerName CustomerEmai l CustomerPhon e
OrderTable --------------- OrderID ProductID ProductName ProductCost
This database was handed to me and I was asked to solve a problem - it lookslike an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14). I'm looking to get a list of all the customers who have ordered product #1,UNLESS they've ordered product #14 in which case I don't want to know aboutthat customer at all. A literal translation could be:
SELECT DISTINCT CustomerID FROM CustomerTable WHERE CustomerID IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 1) AND CustomerID NOT IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 14)
Or:
SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 1 MINUS SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 14
Andy, I don't think the second solution will work. First of all, MINUS is not supported on SQL Server. Second, even if this is run on Oracle, the
two result sets you're performing the minus on are the joined tables, not the single table CustomerTable. So the two sets are disjoint because
ProductID cannot be 1 and 14 simultaneously. So you'll end up with all the
customers who have ordered product #1, regardless of whether they have ordered
product #14 or not.
Sorry didn't notice you're selecting only CustomerID instead of *. It does
work.
My bad. You won the beer. :)
- Dave Since there's a beer involved here, I have to be a bit particular... ;-)
- Dave
-- Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk) Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
SELECT DISTINCT cart_id
FROM OrderTable
WHERE cart_id
IN (
SELECT cart_id
FROM CartTable
WHERE product_index =1 ) AND cart_id NOT
IN (
SELECT cart_id
FROM CartTable
WHERE product_index =14 )
After I switched the fields and table names out to match the real table
names ( they were confusing the issue a bit) I tried the quer(y/ies) and I
get errors on both.
Maybe I should clarify - this is running in a MySQL database server - though
with straight SQL I would think this wouldn't matter much, no?
I moved the structure of the actual tables to a database on my home server
and punched a hole in my firewall to allow you to look at this first hand -
mind you, there are only a few records and they're made up, but they should
be sufficient enough to let you tinker...
surf to http://maple.homelinux.com/phpmyadmin/index.php
account : aaron
pass: pass123
I'll leave it up and running this evening - the account has limited rights
(to that database only)...
take a gander?
BTW - for the speedy response, I'll buy both of you guys a beer...name your
poison!
"Andy Hassall" <an**@andyh.co. uk> wrote in message
news:t5******** *************** *********@4ax.c om... On Sat, 22 Nov 2003 00:52:35 GMT, "news-east.earthlink. net" <ab************ ******@yahoo.no spam.com> wrote:
The scenario:
two tables
CustomerTabl e --------------- CustomerID OrderID CustomerName CustomerEmai l CustomerPhon e
OrderTable --------------- OrderID ProductID ProductName ProductCost
This database was handed to me and I was asked to solve a problem - it
lookslike an inner join solution would apply, but I'm not 100% sure.
There are 14 products total (numbers 1 through 14). I'm looking to get a list of all the customers who have ordered product
#1,UNLESS they've ordered product #14 in which case I don't want to know
aboutthat customer at all.
A literal translation could be:
SELECT DISTINCT CustomerID FROM CustomerTable WHERE CustomerID IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 1) AND CustomerID NOT IN (SELECT CustomerID FROM OrderTable WHERE ProductID = 14)
Or:
SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 1 MINUS SELECT CustomerID FROM CustomerTable INNER JOIN OrderTable USING (OrderID) WHERE ProductID = 14
-- Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk) Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
On Sat, 22 Nov 2003 01:50:17 GMT, "news-east.earthlink. net"
<ab************ ******@yahoo.no spam.com> wrote: Newsgroups: alt.php.sql,com p.databases.ms-sqlserver,micro soft.public.sql server.datamini ng
SELECT DISTINCT cart_id FROM OrderTable WHERE cart_id IN ( SELECT cart_id FROM CartTable WHERE product_index =1 ) AND cart_id NOT IN ( SELECT cart_id FROM CartTable WHERE product_index =14 )
After I switched the fields and table names out to match the real table names ( they were confusing the issue a bit) I tried the quer(y/ies) and I get errors on both.
What errors?
Maybe I should clarify - this is running in a MySQL database server - though with straight SQL I would think this wouldn't matter much, no?
It makes a big difference - MySQL has large gaps in its SQL syntax - in
particular, no subqueries or set operations (i.e. MINUS).
(Subqueries are going into the alpha 4.1 version, I think UNION went into 4.0
at some point, don't know about MINUS).
I moved the structure of the actual tables to a database on my home server and punched a hole in my firewall to allow you to look at this first hand - mind you, there are only a few records and they're made up, but they should be sufficient enough to let you tinker...
surf to http://maple.homelinux.com/phpmyadmin/index.php account : aaron pass: pass123
404 Object not found.
A variation on Dave's query to account for MySQL's limitations and quirks
(identifiers case-sensitive, cannot reference aggregates in HAVING clauses only
their aliases, JOIN must be INNER JOIN) comes up with:
select ct.CustomerID,
count(case ot.ProductID when 1 then 1 else null end) num_1,
count(case ot.ProductID when 14 then 1 else null end) num_14
from CustomerTable ct
inner join OrderTable ot
on (ct.OrderID = ot.OrderID)
group by ct.CustomerID
having num_1 > 0
and num_14 = 0
order by ct.CustomerID
This works against MySQL 3.x, 'cos I just ran it.
--
Andy Hassall (an**@andyh.co. uk) icq(5747695) ( http://www.andyh.co.uk)
Space: disk usage analysis tool ( http://www.andyhsoftware.co.uk/space)
On Sat, 22 Nov 2003 02:06:15 +0000, Andy Hassall <an**@andyh.co. uk> wrote: A variation on Dave's query to account for MySQL's limitations and quirks [...] cannot reference aggregates in HAVING clauses only their aliases, [...]
OK, that's wrong, looks like I was thinking of something else. So going closer
back to Dave's query:
select DISTINCT ct.CustomerID
from CustomerTable ct
inner join OrderTable ot
on (ct.OrderID = ot.OrderID)
group by ct.CustomerID
having count(case ot.ProductID when 1 then 1 else null end) > 0
and count(case ot.ProductID when 14 then 1 else null end) = 0
order by ct.CustomerID;
--
Andy Hassall (an**@andyh.co. uk) icq(5747695) ( http://www.andyh.co.uk)
Space: disk usage analysis tool ( http://www.andyhsoftware.co.uk/space)
"Andy Hassall" <an**@andyh.co. uk> wrote in message
news:du******** *************** *********@4ax.c om... On Sat, 22 Nov 2003 02:06:15 +0000, Andy Hassall <an**@andyh.co. uk> wrote:
A variation on Dave's query to account for MySQL's limitations and
quirks[...] cannot reference aggregates in HAVING clauses only their aliases, [...] OK, that's wrong, looks like I was thinking of something else. So going
closer back to Dave's query:
select DISTINCT ct.CustomerID from CustomerTable ct inner join OrderTable ot on (ct.OrderID = ot.OrderID) group by ct.CustomerID having count(case ot.ProductID when 1 then 1 else null end) > 0 and count(case ot.ProductID when 14 then 1 else null end) = 0 order by ct.CustomerID;
IMHO, no need for the DISTINCT. The "group by ct.CustomerID" will always
give you distinct values of CustomerID.
- Dave -- Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk) Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
On Sat, 22 Nov 2003 02:23:14 GMT, "Dave Hau"
<nospam_dave_no spam_123@nospam _netscape_nospa m.net_nospam> wrote: select DISTINCT ct.CustomerID
[snip] group by ct.CustomerID
[snip]
IMHO, no need for the DISTINCT. The "group by ct.CustomerID" will always give you distinct values of CustomerID.
Ah, yes - that's true.
--
Andy Hassall (an**@andyh.co. uk) icq(5747695) ( http://www.andyh.co.uk)
Space: disk usage analysis tool ( http://www.andyhsoftware.co.uk/space) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ike |
last post by:
Oh I have a nasty query which runs incredibly slowly. I am running MySQL
4.0.20-standard. Thus, in trying to expedite the query, I am trying to set
indexes in my tables.
My query requires four inner joins, as follows :
SELECT DISTINCT
upcards.id,statuskey.status,upcards.firstname,upcards.lastname,originkey.ori
gin,associatekey.username,associatekey2.username,upcards.deleted
FROM upcards,status,origins,associates
INNER JOIN status...
|
by: Prem |
last post by:
Hi,
I am having many problems with inner join. my first problem is :
1) I want to know the precedance while evaluating query with multiple
joins.
eg.
select Employees.FirstName, Employees.LastName, TerritoryID,
Employees.EmployeeID,
RegionID, ProductID
from Employees
|
by: mheydman |
last post by:
I apologize if this has been asked before- I searched google but could
not find a concrete answer.
I recently inherited a database whose t-sql code is written in a format
that I find difficult to read (versus the format I have used for
years).
I have tested the queries below using the SQL Profiler, and both have
identical costs. Is there any advantage of one format over the other?
|
by: Nathan |
last post by:
I have an application that uses an Access database to
gather information on students' test scores. In the
database there are three tables which are joined by one-
to-many relationships: Students, Subjects, and Tests. I
am trying to create a query that joins these three tables
and show all the subjects for only one student, and all
the tests taken in each of those subjects. This is the
query I have entered in the Query Builder:
...
|
by: dmonroe |
last post by:
hi group --
Im having a nested inner join problem with an Access SQl
statement/Query design. Im running the query from ASP and not usng the
access interface at all. Here's the tables:
tblEmployees
empId -- EmpName -- EmpRole -- EmpManager
-------....------------.... ---------....---------------
1........ dan yella..........1..........2
| |
by: MP |
last post by:
Hi
trying to begin to learn database using vb6, ado/adox, mdb format, sql
(not using access...just mdb format via ado)
i need to group the values of multiple fields
- get their possible variations(combination of fields),
- then act on each group in some way ...eg ProcessRs (oRs as RecordSet)...
the following query will get me the distinct groups
|
by: exoskeleton |
last post by:
hi dear experts im here once again...i have a problem on showing the result when im using inner join...here's my code..
$sql_trans_pro_tbl="SELECT transaction_tbl.date_subscribe,transaction_tbl.date_expire".
",product_tbl.pro_id,product_tbl.pro_des FROM transaction_tbl INNER JOIN".
" product_tbl ON transaction_tbl.pro_id=product_tbl.pro_id WHERE".
" transaction_tbl.account_name='$forder_name'";...
|
by: Chamnap |
last post by:
Hello, everyone
I have one question about the standard join and inner join, which one
is faster and more reliable? Can you recommend me to use? Please,
explain me...
Thanks
Chamnap
|
by: Anila |
last post by:
Hi Friends,
My problem with Inner join is ...
first i joined two tables and i got the result.
after that iam trying to join one more table its giving syn tax error in JOIN condition.
Here is the Query
|
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...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |