473,656 Members | 2,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SELECT * FROM "multiple_table s" WHERE "field_(in_thos e_tables)_have_ the_same_paricu lar_value" ?

Hi everybody!

I have several tables from which I want to exract the SAME value (along with
other referenced data).
All the values are in the same column within the tables.
How can I achieve this?

TIA.
Andro
*************** **********
example: (piping bill of material where tables represent piping systems)

TBL1-water
pos. item type size rating
---------------------------------
01 flange 3" 300#
02 valve wafer 2" 150#
03 valve ball 1" 150#
04 elr90 2"

TBL2-oil
(similar like above)......... etc.
----------------------------------

how to select (say) BALL VALVES from these tables along with pos.,size,
rating etc.?
Apr 23 '06 #1
13 2804
On Mon, 24 Apr 2006 00:04:40 +0200, andro wrote:
Hi everybody!

I have several tables from which I want to exract the SAME value (along with
other referenced data).
All the values are in the same column within the tables.
How can I achieve this?

TIA.
Andro
************** ***********
example: (piping bill of material where tables represent piping systems)

TBL1-water
pos. item type size rating
---------------------------------
01 flange 3" 300#
02 valve wafer 2" 150#
03 valve ball 1" 150#
04 elr90 2"

TBL2-oil
(similar like above)......... etc.
----------------------------------

how to select (say) BALL VALVES from these tables along with pos.,size,
rating etc.?


Hi Andro,

SELECT 'water' AS system, pos, item, type, size, rating
FROM TBL1_water
WHERE type = 'ball'
UNION ALL
SELECT 'oil' AS system, pos, item, type, size, rating
FROM TBL2_oil
WHERE type = 'ball'
UNION ALL
etc

But a better solution would be to use just one table, with water/oil/etc
as extra column (part of the primary key), instead of splitting the data
over several similar tables.

--
Hugo Kornelis, SQL Server MVP
Apr 23 '06 #2
Hugo !

Thank you very much for your help.
(I've noticed that such a simple question is not so simple to resolve with
basic SQL knowledge such as mine).
It is difficult to use first approach by entering everytime TBL_NAME (system
here).

Is there any easier way - by using table names as "parameters "?

I like your second approach.
Would you be more specific about "extra column (***part of the primary
key***)"
What do you mean by "part of the primary key"?

Thank you.
"Hugo Kornelis" <hu**@perFact.R EMOVETHIS.info. INVALID> wrote in message
news:f9******** *************** *********@4ax.c om...
On Mon, 24 Apr 2006 00:04:40 +0200, andro wrote:
Hi everybody!

I have several tables from which I want to exract the SAME value (along
with
other referenced data).
All the values are in the same column within the tables.
How can I achieve this?

TIA.
Andro
************* ************
example: (piping bill of material where tables represent piping systems)

TBL1-water
pos. item type size rating
---------------------------------
01 flange 3" 300#
02 valve wafer 2" 150#
03 valve ball 1" 150#
04 elr90 2"

TBL2-oil
(similar like above)......... etc.
----------------------------------

how to select (say) BALL VALVES from these tables along with pos.,size,
rating etc.?


Hi Andro,

SELECT 'water' AS system, pos, item, type, size, rating
FROM TBL1_water
WHERE type = 'ball'
UNION ALL
SELECT 'oil' AS system, pos, item, type, size, rating
FROM TBL2_oil
WHERE type = 'ball'
UNION ALL
etc

But a better solution would be to use just one table, with water/oil/etc
as extra column (part of the primary key), instead of splitting the data
over several similar tables.

--
Hugo Kornelis, SQL Server MVP

Apr 23 '06 #3
On Mon, 24 Apr 2006 00:46:02 +0200, andro wrote:
Hugo !

Thank you very much for your help.
(I've noticed that such a simple question is not so simple to resolve with
basic SQL knowledge such as mine).
It is difficult to use first approach by entering everytime TBL_NAME (system
here).
Hi Andro,

I'm sorry, I don't understand this part of your message.

Is there any easier way - by using table names as "parameters "?
There is, but it's not recommended, because of the security
implications. If you want to read about the method *and* the risks it
has, go to http://www.sommarskog.se/dynamic_sql.html.

I like your second approach.
Would you be more specific about "extra column (***part of the primary
key***)"
What do you mean by "part of the primary key"?


That would be easier to answer if you had told me exactly how yoour
tables currently look.

I'll use a made-up example to illustrate this. Consider the following
(bad!) design for daily sales data:

CREATE TABLE North_Sales
(SaleDate smalldatetime NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products
)
CREATE TABLE East_Sales
(SaleDate smalldatetime NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products
)
(and two more for regions South and West)

These four tables can and should be replaced by this single table:

CREATE TABLE Sales
(SaleDate smalldatetime NOT NULL,
Region char(5) NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, Region, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products,
CHECK (Region IN ('North', 'South', 'East', 'West'))
)

Notice how I added a column "Region", _AND* added this column to the
list of columns that make up the primary key.

(I also added a check constraint - this should be replaced by a FOREIGN
KEY constraint if there's a Regions table in the database as well).

--
Hugo Kornelis, SQL Server MVP
Apr 23 '06 #4
Hugo!

Thanx again for your help.
Regarding the first part.....nothin g special - it's just that I'm kinda
bored to repeatedly enter nearly the same query for every system here.
(There are not just several but say 40-50 which are changing from project to
project.)
I just wondered (please note: I'm a newbie) is there a way to instruct the
system in a kind of "loop" DO - UNTIL or FOR/NEXT for every system table in
database to repat the qurey within the tables using "parameter" TBL_NAME
where neccessary. Some kind of automation maybe - you know. (Seems very
advanced request).
(I heaven't checked your link yet ).

Second part of yours is advanced to me.
Seems that I have to try harder from now on.

Thank you for your time.
"Hugo Kornelis" <hu**@perFact.R EMOVETHIS.info. INVALID> wrote in message
news:kr******** *************** *********@4ax.c om...
On Mon, 24 Apr 2006 00:46:02 +0200, andro wrote:
Hugo !

Thank you very much for your help.
(I've noticed that such a simple question is not so simple to resolve with
basic SQL knowledge such as mine).
It is difficult to use first approach by entering everytime TBL_NAME
(system
here).


Hi Andro,

I'm sorry, I don't understand this part of your message.

Is there any easier way - by using table names as "parameters "?


There is, but it's not recommended, because of the security
implications. If you want to read about the method *and* the risks it
has, go to http://www.sommarskog.se/dynamic_sql.html.

I like your second approach.
Would you be more specific about "extra column (***part of the primary
key***)"
What do you mean by "part of the primary key"?


That would be easier to answer if you had told me exactly how yoour
tables currently look.

I'll use a made-up example to illustrate this. Consider the following
(bad!) design for daily sales data:

CREATE TABLE North_Sales
(SaleDate smalldatetime NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products
)
CREATE TABLE East_Sales
(SaleDate smalldatetime NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products
)
(and two more for regions South and West)

These four tables can and should be replaced by this single table:

CREATE TABLE Sales
(SaleDate smalldatetime NOT NULL,
Region char(5) NOT NULL,
ProductNo int NOT NULL,
AmountSold int NOT NULL,
PRIMARY KEY (SaleDate, Region, ProductNo),
FOREIGN KEY (ProductNo) REFERENCES Products,
CHECK (Region IN ('North', 'South', 'East', 'West'))
)

Notice how I added a column "Region", _AND* added this column to the
list of columns that make up the primary key.

(I also added a check constraint - this should be replaced by a FOREIGN
KEY constraint if there's a Regions table in the database as well).

--
Hugo Kornelis, SQL Server MVP

Apr 23 '06 #5
> That would be easier to answer if you had told me exactly how yoour
tables currently look.

Tables look like this:
*************** **********
example: (piping bill of material where tables represent piping systems)

TBL1-water
pos. item type size rating operation pcs. material
identification_ no ( <-----unique ! )
-----------------------------------------------------------------------------------
01 flange 3" 300# NULL 2 AISI316L
012324585
02 valve wafer 2" 150# hydraulic 3 CS/SS
065898329
03 valve ball 1" 150# manual 1 BZ/BZ
378987548
04 elr90 2" NULL 8 CS
879539287
05 etc......

TBL2-oil
(similar like above)......... etc.

TBL3-gas
---------------

identification_ no is unique across the tables (same item type has one)
Apr 24 '06 #6
>> .. repeat the qurey within the tables using "parameter" TBL_NAME
where neccessary. <<

You need to change your ENTIRE MENTAL MODEL. You are still thinking in
terms of a file system model of data. A table models a set of one and
only one kind of entity. Thus passing a table name to a procedure is
totally wrong. Your procedure would lack any coupling and cohesion.
It would be named the "Britney Spears, Squids and/or Automobiles"
procedure, so generic as to be unmaintainable.

The design flaw Hugo showed you is called "attribute splitting" -- a
table is split up on the values of an attribute.

Apr 24 '06 #7
On Mon, 24 Apr 2006 01:55:24 +0200, andro wrote:
That would be easier to answer if you had told me exactly how yoour
tables currently look.

Tables look like this:


Hi Andro,

Thanks for giving an example, but it doesn't tell me enough. Could you
please post the DDL (CREATE TABLE statements, including all constraints
and indexes) for the tables?

Also, you write:
TBL1-water
pos. item type size rating operation pcs. material
identification _no ( <-----unique ! )
I'm not sure if I interpret the uniqueness of the identification_ no
correct. (Please bear in mind that Ennlgish is not my native language
and that I know nothing about piping systems - most of the terms in your
example are Greek to me!)

I assume that it's impossible to have the same identification_ no on two
rows in table TBL1-water. But can the same identification_ no still be in
one of the other tables? And if so, what restrictions hold for the other
columns? Or to use a concrete example: given this population of
TBL1-water:
TBL1-water
pos. item type size rating operation pcs. material
identification _no ( <-----unique ! )
-----------------------------------------------------------------------------------
01 flange 3" 300# NULL 2 AISI316L
012324585
02 valve wafer 2" 150# hydraulic 3 CS/SS
065898329
03 valve ball 1" 150# manual 1 BZ/BZ
378987548
04 elr90 2" NULL 8 CS
879539287
05 etc......
Would this population of TBL2-oil be possible:
TBL2-oil
pos. item type size rating operation pcs. material
identification _no ( <-----unique ! )
-----------------------------------------------------------------------------------
01 foo bar 2" 200# automatic 7 KG/H33C
477396411
02 flange wafer 2" 250# electric 3 CS/SS
378987548
03 etc......


Note that I copied identification_ no 378987548 over to the second table,
but I changed all the other columns. Is this a vallid example? If not,
why not? Just because the same identification_ no is in both tables, or
because it is in two tables with different columns? And should ALL
columns be the same, or just some? Which? What should I correct at
minimum in TBL2-oil to make this an allowed example?

With the answers to those questions, I can probably help you a lot
further along the way.

--
Hugo Kornelis, SQL Server MVP
Apr 24 '06 #8
andro (av*@email.t-com.hr) writes:
Regarding the first part.....nothin g special - it's just that I'm kinda
bored to repeatedly enter nearly the same query for every system here.
(There are not just several but say 40-50 which are changing from
project to project.) I just wondered (please note: I'm a newbie) is
there a way to instruct the system in a kind of "loop" DO - UNTIL or
FOR/NEXT for every system table in database to repat the qurey within
the tables using "parameter" TBL_NAME where neccessary. Some kind of
automation maybe - you know. (Seems very advanced request).
You can do this:

exec sp_MSforeachtab le 'SELECT COUNT(*), ''?'' FROM ?'

But this is mainly good for admin tasks. And it is undocumented and
unsupported.

The reason that there is not any more civilised way to this is that
it is not meaningful. In a well-designed database, each table is
supposed to describe a unique entity, and thus each table has a
different layout and running the same query on several tables is not
possible, unless it's a trivial one like the SELECT COUNT(*) in the
example above.

If you have a database where you have a lot of tables with the same
structure, then you have a poorly designed database. Best would be
to unite the tables into one - or construct a partitioned view over
the tables, and then run the queries against that view.
(I heaven't checked your link yet ).


In case you have multiple tables wthe same layout, look particularly
at http://www.sommarskog.se/dynamic_sql.html#Sales_yymm.


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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Apr 24 '06 #9
av1
I accept that this is bad database design.
(Any help toward improving it is appreciated, TIA)
But this is a "real world" example.

Designers are working on project consisting of several piping systems
(say 30) preparing (separate) bills of materials (BOMs) for each system
(water, oil, fuel, steam etc). BOMs looks similar to "TBL1_water " shown
at the beginning.
Later on - the project manager wants to know how many similar items we
have accross the project for purchasing purposes (discounts). He wants
to group similar items say ball valves or flanges for bidding purposes.
Regarding the table look - they use primarily Excel ( ** don't blame me
here ! ** )
I know that we need more advanced tool. That's why I raised this
question here.
Anyway, we can use this *.xls files more or less efficiently. (not to
mention problems with inconsistency with naming conventions, formats
etc. which exists ).
Question still remains: how to SELECT similar data of interest across
many tables?

Regarding the "identification _no": this data will be populated later on
after retrieving the data of interest (in question above), selecting
the supplier and after purchasing the items so it is not important in
the initial stage.
It is unique mark for the same item and same type across all the tables
(Say
ball valve with size 1", rated pressure 150#, manually operated and
made of bronze has assigned it's own identification_ no (at
will) across the all tables. Similar valve type (ball) with all the
items the same except one (say different material ) has different
indent_no).
Take a shoe store example:
Maker Model size color ident_no
---------------------------------------------------------------------------
Clarks XY 11 black 1
Clarks XY 11 grey 2
Clarks XY 12 grey 3

etc...
(database guru would not prepare the table like this - this is only for
interpretation)

Generally, I assume that all the tables should be kept in one table
with one additional distinct column data representing the "system" at
every corresponding row.

Apr 25 '06 #10

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

Similar topics

1
5242
by: JT | last post by:
I have an input form for which I've created a "matrix" for user input. Basically, the user chooses a radio button and then through javascript, a select box is displayed to define a value for that radio option, like so: Choice: (Radio1) type: (select box1) Choice: (Radio1) type: (select box2) Choice: (Radio1) type: (select box3) Choice: (Radio1) type: (select box4) Choice: (Radio1) type: (select box5)
21
5245
by: John Fabiani | last post by:
Hi, I'm a newbie and I'm attempting to learn howto create a select statement. When I use >>> string1='18 Tadlock Place' >>> cursor.execute("SELECT * FROM mytest where address = %s",string1) All works as expected. But >>> numb=10 >>> cursor.execute("SELECT * FROM mytest where clientID = %d",numb) Traceback (innermost last): File "<stdin>", line 1, in ?
3
8097
by: Memduh Durmaz | last post by:
Hi, I'm using DB2 UDB 7.2. Also I'm doing some tests on SQL Server 2000 for some statements to use efectively. I didn't find any solution on Sql Server about WITH ... SELECT structure of DB2. Is there any basic structure on Sql Server like WITH ... SELECT structure?
4
6431
by: point | last post by:
Hello there... I'm a PHP programmer and starting to learn JS... I have a following problem.... I have 3 select boxes! one is hotel one is destination and one is country... if someone clicks selects the country then the destination select box shows the destinations in that country and further if he chooses destination all
1
5512
by: Carl Wu | last post by:
Hi all, I am newcomer in HTML, Javascript, I want to create two select controls S1, S2. There are 3 options: ALL, A, B in S1; When select A in S1, It let you select A1, A2 in S2,
18
4046
by: CJM | last post by:
I'm building a search function for one of my applications. The user has the option to enter a number criteria of criteria, but none are compulsary. I need to be able to build up a query string that includes only the right criteria. The simplest way I have found is something like this: sSQL = "Select field1, field2, etc form table where 1=1" If Request.Form("Criteria1") <> "" then sSQL = sSQL & " and criteria1 = " &...
2
7918
by: Chris Becker | last post by:
I have the following query: SELECT Month, Sum(Hits) AS Hits FROM tblHits GROUP BY Month ORDER BY Month Unfortunately it only returns rows for months that have data assigned to them. How can I tweak this so that months 1-12 are returned, and Hits = 0 for months with no data in the base table?
1
2965
by: serena.delossantos | last post by:
Trying to insert into a history table. Some columns will come from parameters sent to the store procedure. Other columns will be filled with a separate select statement. I've tried storing the select return in a cursor, tried setting the values for each field with a separate select. Think I've just got the syntax wrong. Here's one of my attempts: use ESBAOffsets go
6
3392
by: Apaxe | last post by:
In the database i have a table with this information: key_id =1 key_desc =43+34+22+12 I want sum the values in key_desc. Something like: SELECT key_desc FROM table But the result of the select was "111" and not "43+34+22+12".
0
30374
by: Gordon Padwick | last post by:
A form contains controls, one or more of which can be other forms. A form that contains another form is known as a main form. A form contained by a main form is known as a subform. A subform itself can contain other forms, sometimes known as subsubforms. This article deals only with main forms and their immediate subforms. The books about Access I’ve read contain some useful information about subforms, but don’t adequately cover the matter of...
0
8382
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
8297
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
8816
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
8717
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
8600
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
7311
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
6162
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
4150
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...
2
1930
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.