473,396 Members | 1,918 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

SELECT * FROM "multiple_tables" WHERE "field_(in_those_tables)_have_the_same_paricular_v alue" ?

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 2769
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.REMOVETHIS.info.INVALID> wrote in message
news:f9********************************@4ax.com...
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.....nothing 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.REMOVETHIS.info.INVALID> wrote in message
news:kr********************************@4ax.com...
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.....nothing 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_MSforeachtable '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****@sommarskog.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
av1
Sorry - I forgot

What would be the syntax to include additional column data representing
the "system" in a combined table ?

Apr 25 '06 #11
(av*@email.t-com.hr) writes:
Question still remains: how to SELECT similar data of interest across
many tables?

What would be the syntax to include additional column data representing
the "system" in a combined table ?


SELECT system = 'system of tbl1', col1 ,col2, col2,
FROM tbl1
WHERE ...
UNION ALL
SELECT 'system2, col1, col2, col3,
FROM tbl2
WHERE ...
UNION ALL

If the WHERE clause is generally applicable, you can do:

SELECT system, co1l, col2, col3, ...
FROM (SELECT system = 'system of tbl1', col1 ,col2, col2,
FROM tbl1
UNION ALL
SELECT 'system2, col1, col2, col3,
FROM tbl2
UNION ALL
...) AS x
WHERE ...

Here I'm using a derived table, which logically a temp table within
the query, but not necessarily comnputed as such. That is the optimizer
may recast the computation order for better effeciency.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.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 25 '06 #12
On 25 Apr 2006 03:41:43 -0700, av*@email.t-com.hr wrote:
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?
Hi Andro,

And the answer still remains that this is VERY easy if you use just one
table instead of 30 tables for the 30 piping systems.

In my previous message, I asked you to post the DDL (CREATE TABLE
statements, including all constraints and indexes) for the tables that
you are currently using. If you had done that, I could now have given
you the CREATE TABLE statement for the single table to replace your 30
current 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).
Okay. So what exactly does this mean for the sample population for two
of the current tables that I posted? Is that particular combination of
vallues logically permitted? If not, what column(s) need to be changed
and why?
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.


Yes.

--
Hugo Kornelis, SQL Server MVP
Apr 26 '06 #13
Amit (co***********@gmail.com) writes:
I am able to retrive the uncommon columns from two similar tables, but
the problem is i require a query, which can help me to find out which
columns are added separately. Another query which can say which columns
are deleted. And the last one can say which column has changed .
It is not clear if you are looking for metadata information or data. But
I assumed that you want to compare the metadata for two tables.

This may get you started:

select a.tblname, a.colname, a.typename, a.max_length,
b.tblname, b.colname, b.typename, b.max_length
from (SELECT tblname = o.name, colname = c.name,
typename = t.name, c.max_length
FROM sys.objects o
JOIN sys.columns c ON o.object_id = c.object_id
JOIN sys.types t ON t.system_type_id = c.system_type_id
AND t.user_type_id <= 255
WHERE o.name = 'tbl1') AS a
full join
(SELECT tblname = o.name, colname = c.name,
typename = t.name, c.max_length
FROM sys.objects o
JOIN sys.columns c ON o.object_id = c.object_id
JOIN sys.types t ON t.system_type_id = c.system_type_id
AND t.user_type_id <= 255
WHERE o.name = 'tbl2') AS b
ON a.colname = b.colname
AND a.typename = b.typename
AND coalesce(a.max_length, 0) = coalesce(b.max_length, 0)
WHERE a.colname IS NULL OR b.colname IS NULL

This query is for SQL 2005. If you are on SQL 2000, the query is similar,
but you need to use sysobjects, syscolumns and systypes, and somewhat
different colunm names. You could look that up in Books Online.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.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
Dec 4 '07 #14

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

Similar topics

1
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...
21
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...
3
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. ...
4
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...
1
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
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...
2
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...
1
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...
6
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...
0
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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,...

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.