473,657 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sql LEFT JOIN and IN question

I'm trying to select records from two tables. the following code works for
what i want to to:

set RSMain = conn.execute ( "select top 20 product, prodcode, edition, (
select count(id) from cartTemp where convert(varchar (4000),cartdeta ils) in
(a.prodcode)) as counter from Products a where isOffer = 0 order by
prodcode")
do until RSMain.EOF

set RSCheck = conn.execute ("select count(id) as counter from cartTemp where
cartdetails like '%" & RSMain("prodcod e") & "|%' ")

if NOT RSCheck.EOF then if RSCheck("counte r") > 0 then response.write
RSMain("product ") & ": " & RSMain("edition ") & " is in " & RSCheck("counte r")
& ":" & RSMain("counter ") & " shopping carts. "

RSMain.movenext
loop

but i was hoping to be able to simplify it thusly to avoid the second lookup

set RSMain = conn.execute ( "select top 20 product, prodcode, edition,
count(b.id) as counter from Products a join cartTemp b on
convert(varchar (4000),b.cartde tails) in (a.prodcode) where isOffer = 0 group
by a.product,a.edi tion,a.prodcode order by prodcode")

which doesn't fail, but returns a 0 count on the RSMAin("counter ") ...

I guess i'm trying to use "in" as a replacement for "like '%ANYQUERY%', but
of course i don't yet know what ANYQUERY is...

any thoughts greatly appreciated
Jul 23 '05 #1
8 2512
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

What you did post is confusing. For example, you have the vague name
"id" without tellling us what it identifies, you use aliases that make
no sense to the reader, cart_details is plural so it cannot be a data
element (it seems to be prod_code under a second name), isoffer looks
like you are writing SQL with Boolean bit flags, I can only hope that
CartTemp is not a temporary table, etc. Ihave teh feeling thatyou are
writing a tape file system where you build a query in procedural steps
and not a relational query at all.

And you never told us what you want to do.

The best I can pull out and put into SQL is:

SELECT P.product_name, P.product_editi on, P.prod_code,
COUNT(C.prod_co de) AS cart_tally
FROM Products AS P,
CartTemp AS C
WHERE C.prod_code = P.prod_code
AND P.isoffer = 0
GROUP BY P.product_name, P.product_editi on, P.prod_code;

I am guessing that you want the tally of how many times a product was
in CartTemp. You do not need loops for that.

Jul 23 '05 #2
niceguy (ni*****@hotmai l.com) writes:
but i was hoping to be able to simplify it thusly to avoid the second
lookup

set RSMain = conn.execute ( "select top 20 product, prodcode, edition,
count(b.id) as counter from Products a join cartTemp b on
convert(varchar (4000),b.cartde tails) in (a.prodcode)
where isOffer = 0
group by a.product,a.edi tion,a.prodcode order by prodcode")

which doesn't fail, but returns a 0 count on the RSMAin("counter ") ...

I guess i'm trying to use "in" as a replacement for "like '%ANYQUERY%',
but of course i don't yet know what ANYQUERY is...


I've been looking at this for several minutes now, but I've come to the
conclusion that I have only have information enough for bad guesses. So
I suggest that you post:

o CREATE TABLE statements for your table.
o INSERT statements with sample data.
o The desired output given the sample.
o A short narrative of what you want to achieve.

This is the standard recommendation when people ask for help with
queries. By including all of these you can get a tested query in
response. The less you include, the less you get in response, both
in terms of quantity and quality.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
In addition to the comments of Joe and Erland I would like to know why
you have dynamic SQL running in your VB app instead of using stored
procedures. I hope you understand the implications of what you have
done.

--
David Portas
SQL Server MVP
--

Jul 23 '05 #4
On Sun, 20 Feb 2005 00:14:44 +0000, David Portas wrote
(in article <11************ ********@f14g20 00cwb.googlegro ups.com>):
In addition to the comments of Joe and Erland I would like to know why
you have dynamic SQL running in your VB app instead of using stored
procedures. I hope you understand the implications of what you have
done.


....

On Sat, 19 Feb 2005 22:08:36 +0000, CELKO-- wrote
(in article <11************ **********@z14g 2000cwz.googleg roups.com>):
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

thanks for your replies - I'll try to rephrase the query sensibly in a
reply... By the way, the answer is no, I don't know the implications - all i
know is stored procedures are a pain in the proverbial - what are the
implications? When i do speed comparisons between dynamic and stored
procedures the speed is the same.

But I'm pretty ignorant of the technical side :(

Jul 23 '05 #5
niceguy (ni*****@hotmai l.com) writes:
thanks for your replies - I'll try to rephrase the query sensibly in a
reply... By the way, the answer is no, I don't know the implications -
all i know is stored procedures are a pain in the proverbial - what are
the implications? When i do speed comparisons between dynamic and stored
procedures the speed is the same.


Whether stored procedures are a pain anywhere depends a little on your
architcure and your application. The main issue here is not performance,
but security, from two points of view: 1) general permissions 2) SQL
injection.

General permissions: Having the SQL code in the VB code, means that the user
that runs the VB code must have permissions to access the tables. This means
that if this users gets access to the database by other means than the
application, he may be able to access and update data in ways that he maybe
shouldn't.

Now, this may or may not be an issue. Here are at three possible reasons
why it might not: a) Your code runs in a middle tier that authenticate
the users, and then logs into the into SQL Server with a general login,
and the users does not even have direct permission to the database. b)
you are using application roles, and all rights have been granted to the
application role. c) business rules are such that users are permitted to
access the database directly anyway, and your application is just a helper
for them.

2) SQL injection. Even if a) or b) applies to you, you still have to worry
about SQL injection. In the sample you posted the risk for SQL injection
is low, since data you insert comes from the database. But consider:

set RSCheck = conn.execute ("select count(id) as counter from cartTemp
where cartdetails like '%" & RSMain("prodcod e") & "|%' ")

Assume now that prodcode contains a single quote. Assume further that
the single quote is followed by " DROP TABLE tbl --". You will then have
an SQL batch that performs something that you intended. Of course, that
product code would like this is unlikely, but assume instead input from
a malicious user. Even if you don't have a mailicious user, assume that
you have a user who tries to enter the name O'Brien.

The way to address SQL injection is not stored procedure per se, but to
use parameterised commands. See this link for a quick example:
http://authors.aspalliance.com/steve...les/sprocs.asp. Although
this example uses stored procedure, you can to the same with bare SQL
statements as well by using ? as placeholder for parameters.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #6
select top 20 product, prodcode, edition, count(b.id) as counter from
Products a
join cartTemp b on convert(varchar (4000),b.cartde tails) LIKE
'%'+cast(a.prod code as varchar)+'|%'
where isOffer = 0
group a.product, a.edition, a.prodcode order by prodcode

this mirrors what you are trying to acheive with the code you use in your
inner loop and the join will eliminate products with no cart records
removing the need for the check on counter>0 (substitute left join to put
them back in), although there are a few notes.

1) you will have trouble if you have a product 'abcd' and a product 'bcd'
as checking for carts containing 'bcd' will count carts containing 'abcd'.
To solve this with minimum modification to the code, put a prefix as well as
a suffix on the comparison:

'|'+convert(var char(4000),b.ca rtdetails) LIKE '%|'+cast(a.pro dcode as
varchar)+'|%'

2) using cartdetails in this way to store a list of items makes manipulation
more difficult then necessary and <B>Criples</B> performace. Consider using
the carttemp table for the cart itself and a cartitem table representing the
entities within the cart.

3) stored procedures are better both for performance and security reasons
than raw T-SQL. I started my coding life asp writing code similar to your
example, over time through experience and understanding, I moved completely
to stored procedures and there is absolutely no downside to the migration.

Mr Tea

"niceguy" <ni*****@hotmai l.com> wrote in message
news:00******** *************** ******@news.ast raweb.com...
I'm trying to select records from two tables. the following code works for
what i want to to:

set RSMain = conn.execute ( "select top 20 product, prodcode, edition, (
select count(id) from cartTemp where convert(varchar (4000),cartdeta ils)
in
(a.prodcode)) as counter from Products a where isOffer = 0 order by
prodcode")
do until RSMain.EOF

set RSCheck = conn.execute ("select count(id) as counter from cartTemp
where
cartdetails like '%" & RSMain("prodcod e") & "|%' ")

if NOT RSCheck.EOF then if RSCheck("counte r") > 0 then response.write
RSMain("product ") & ": " & RSMain("edition ") & " is in " &
RSCheck("counte r")
& ":" & RSMain("counter ") & " shopping carts. "

RSMain.movenext
loop

but i was hoping to be able to simplify it thusly to avoid the second
lookup

set RSMain = conn.execute ( "select top 20 product, prodcode, edition,
count(b.id) as counter from Products a join cartTemp b on
convert(varchar (4000),b.cartde tails) in (a.prodcode) where isOffer = 0
group
by a.product,a.edi tion,a.prodcode order by prodcode")

which doesn't fail, but returns a 0 count on the RSMAin("counter ") ...

I guess i'm trying to use "in" as a replacement for "like '%ANYQUERY%',
but
of course i don't yet know what ANYQUERY is...

any thoughts greatly appreciated

Jul 23 '05 #7
>> all I know is stored procedures are a pain in the proverbial - what
are the implications? <<

No, they are pretty easy in T-SQL. It is a small language designed for
such short jobs inside the database. The syntax is from the Algol
family by way of C.
When I do speed comparisons between dynamic and stored procedures

the speed is the same. <<

Wait until you scale up and have network between the front end the
database. You will see a large difference. You also get better
control over the user access and better data integrity.

Jul 23 '05 #8
See Erland's reply.

Also note that putting your data access code on the server simplifies
maintenance. You won't have to re-test and re-deploy your application
for every schema change.

Stored procedures shouldn't be a pain. They are the most powerful
tool at your disposal for data access purposes.

--
David Portas
SQL Server MVP
--

Jul 23 '05 #9

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

Similar topics

0
2357
by: Soefara | last post by:
Dear Sirs, I am experiencing strange results when trying to optimize a LEFT JOIN on 3 tables using MySQL. Given 3 tables A, B, C such as the following: create table A ( uniqueId int not null default 0 auto_increment, a1 varchar(64) not null default '',
0
1797
by: Justin | last post by:
Hi. I decided to tidy up some of my queries, but I came across something that stumpt me: mysql> SELECT -> jobs.jobId, -> jobs.active, -> jobs.title, -> jobs.listed, -> industries.industry, -> occupations.occupation,
1
3441
by: Paul Bramscher | last post by:
Here's one for pathological SQL programmers. I've got a table of things called elements. They're components, sort of like amino acids, which come together to form complex web pages -- as nodes in trees which form parent-child relationships, sort of like newsgroups. For example, the parent_id field points to another element. Indent_level is there for denormalization purposes, to avoid costly recursive issues in querying. The...
2
2736
by: Scott Snella | last post by:
Hi, I hope this is the right place to post, but, I am having a problem with an UPDATE command and a LEFT JOIN, I am using something like: UPDATE table_a LEFT JOIN table_b ON table_a.field1=table_b.field1 SET table_b.field6='1' WHERE table_a.field2='1'; Something along those lines. Anyway, from what I can see on various web sites, documentation, etc, I think it should work, however, I keep getting this error...
4
4100
by: jbm05 | last post by:
Hi, I'm curious about the computational complexity of a query I have. The query contains multiple nested self left joins, starting with a simple select, then doing a self left join with the results, then doing a self left join with those results, etc. What puzzles me is that the time required for the query seems to grow exponentially as I add additional left joins, which I didn't expect. I expected the inner select to return about 25...
3
23088
by: Ian Boyd | last post by:
i know nothing about DB2, but i'm sure this must be possible. i'm trying to get a client to create a view (which it turns out is called a "Logical" in DB2). The query needs a LEFT OUTER JOIN, but he doesn't know how to do that, or even if he can, and i don't have to time to learn DB2 from scratch right now. The following SQL Query is a trimmed sample of the full View (i.e. Logical) definition - and i would create it on an SQL based...
14
6089
by: Ryan | last post by:
I want to do the following SQL statement in Access. However, it won't allow me to have the secondary part of my join statement and tells me that this is not supported. OK, so Access doesn't support it, but there must be an alternative. I can add the part 'D.Dealer_Code' to the where clause, but because of the way that the statement is executed, it excludes data that I want. My SQL statement is perfectly leagal and works fine, but Access...
5
2288
by: Dev | last post by:
Hello all, I need to do a left out join where a.field1 ilike %b.field2% But I can not figure out the exact syntax to using the ilike in the join? ----------
0
1090
by: tricard | last post by:
Good day all, I have four tables that I am attempting to LEFT JOIN together in a query: tblPartNumber (PartNumberID is primary key autonumber) tblPartNumberVendor (PartNumberVendorID is primary key autonumber) tblPartNumberSupplier (PartNumberSupplierID is primary key autonumber) tblPartNumberCost (PartNumberCostID is primary key autonumber) The relationships are as follows:
3
2690
by: rrstudio2 | last post by:
If I have two tables and need to do a left outer join and include a where statement on the second table, it seems like the left outer join becomes an inner join. For example: Table: Names id Name StatusCode 1 John 11 2 Henry 22 3 Bob 33
0
8326
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,...
0
8845
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
8743
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
8622
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
7355
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
6177
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
5647
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();...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.