Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




UNION, Individually Works Fine, But Not In Union


Well, I am using an UNION, and while both of the queries works fine while used individually, they don't work while in the UNION.

Here is the code -

PHP

(
SELECT *
FROM job
WHERE date_fin !=0000-00-00
ORDER BY date_fin ASC
)
UNION (
SELECT *
FROM job
WHERE date_fin =0000-00-00
ORDER BY date_creation ASC
)

What do u think guys?

Note : MySQL version 4.1.21

Note : Not working means, this part is not working => 'ORDER BY date_fin ASC', means, the returned results are not ordered as I want.

MySQL doc. tells,

To apply ORDER BY or LIMIT to an individual SELECT, place
the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
UNION - Works In 4.0.16, Not In 4.1.8
I have a query that works in 4.0.16 on my web host, but not 4.1.8 on my dev. box. Web host is upgrading in 10 days.

Notes:
Server language is ColdFusion
gamedate is type DATE

SELECT DISTINCT gamedate
FROM schedule
WHERE gamedate >= now()
UNION (
(SELECT DISTINCT gamedate
FROM schedule
WHERE gamedate < now()
ORDER BY gamedate desc LIMIT 1)
ORDER BY gamedate asc LIMIT 3

The goal is to select the most recent gamedate prior to "today" and the next two game dates including "today".

SQL Query Works Fine With Phpmyadmin But Gives Me No Results And EOF With ASP
I have a strange problem: when I perform a sql query on my phpmyadmin it works fine and it gives me the right results. If I perform the _same_ query through my asp application I reach immediately the EOF condition without any results!

Error With SQL Statement When Using MySQL 5.0.24 (Works Fine In MySQL 4.0)
Here is my query that worked in mySQL 4.0 but not in MySQL 5.0.24:

INSERT INTO magtallynew SET magempnum=?', magcentre='YVRRC', entrydate=&#55614;&#57158;-08-15', empnum=?', empcentre='YVRRC', connection='Rockwell', service='Express', region='dom', callertype='CSR', otherdept='', transferredcall='No', directrespdept='No', station='Not Applicable', withoutmagassist='Yes', category='Accounting', issue='Advised On Contact', comments='test'

Here is the error message I get:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'connection='Rockwell', service='Express', region='dom', callertype='CSR', otherd' at line 1

Union Without Union
I am running version 3.23 of MySQL. It does not allow UNION statements.
How can I pull this off without a union. I hear it can be done with a LEFT JOIN

SELECT `id`,`name`,`date_of_event` FROM `events` ORDER BY `date_of_event` ASC
UNION
SELECT `id`,`name`,`date_of_event` FROM `upcoming` ORDER BY `date_of_event` ASC

Using UNION
(SELECT id,name FROM table1)
UNION
(SELECT id,name FROM table2)
UNION
(SELECT id,name FROM table3)
order by name limit 1;

this query is works. I can get the fields values. But i cant get the owner table that i read. for example i get this values 3,george

(which table has this record???)

UNION On Ver. 3.23
Are there any alternatives to UNION? Running mySQL ver. 3.23
Upgrade is not an option!

My query looks like this:

(SELECT sum(t.timer) AS sumtimer FROM emply
WHERE t.tmnr = 1 AND t.tjobnr = 69 AND
t.tfaktim = 2 AND t.tdato BETWEEN '05/7/4' AND '06/2/1')

UNION (

SELECT sum(f2.timer) AS fakbare FROM timer f2 WHERE
f2.tjobnr = 69 AND f2.tmnr = 1 AND f2.tfaktim = 1 AND f2.tdato BETWEEN '05/7/4' AND '06/2/1')

Union
I have X number of identical (structure-wise) tables, with  one generated for every day.  There is a reporting tool which requires that certain data be extracted for a given time period, which can span any number of these databases.  My idea is to use a dynamically generated UNION ALL statement which simply joins identical selects for each table.  e.g.

CODESELECT id, blah, bleh FROM t1
UNION ALL
SELECT id, blah, bleh FROM t2
....

UNION HELP
I have written a PHP search App and I want it to search between like 8 or so tables in one Database.

Here is my union mysql code:

$query = "(select * from arcamax where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from drudge where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from google where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from human_events where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from newsmax where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from street where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from townhall where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from weatherbug where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") union (select * from worldnet where promo_code like "%$trimmed%" or start_end_date like "%$trimmed%" or mailedlist like "%$trimmed%" or description like "%$trimmed%" or orders like "%$trimmed%" or totalrevenue like "%$trimmed%") order by mailedlist";

Now if I run a search with the above code it does not work...but if I limit the number of tables to two it works fine.

How To Do A Union
I have a query I need to do that combines two queries The structure for the first table is

Application_Period
CampusID
GroupID
IndivID

This table uses the lookup table Time to get the groupID and IndivID.

TimeID
Application_Period

TimeID matches GroupID and IndivID. How can I combine the two tables into one without the UNION operator?

Using Union
i have two tables, "txns" and "proc". "txns" has 100 records while "proc" has 55 records. All records in "proc" table can also be found in "txns" table. I mean all those 55 records in proc are also in txns.

(txns - proc)
txns=100 records
-
proc=55 records
------------------
45 records that have no match

the question.

What must i do to find those records that dont have a match in txns table and view those unmatched records

UNION
I have a problem with the use of UNION. If I query my database with the following:

Quote: SELECT column1 FROM mytable WHERE title = "mytitle" UNION SELECT column1 FROM mytable WHERE author = "myauthor"

I get a syntax error! (#1064) Why? I can;t find anything wrong in the query above.

Union
I have the following code

SELECT year, count(*) FROM test1 GROUP BY year UNION ALL SELECT year, count(*) FROM test2 GROUP BY year";

This query is fine but I have to be able to add the totals for example if table test1 has the value 2007 and count 5 and table test2 has the value 2007 and count 5. I have to be able to store this in an array as 2007, 10.

Not In + Union
got tables brochure_applied, and brochure_content_protected, and brochure_user_protected. each has the column bid. brochure applied also has uid.
uid is the reference key (as shown in my example query).
i basically wanna get all the bids from brochure_applied that have uid = 3, but remove all the bids that are either in brochure_content_protected and also brochure_user_protected.

my query is: select bid from brochure_applied where uid=3 not in ((select bid from brochure_content_protected) union (select bid from brochure_user_protected))

UNION
it's my command:
select name from users where userid=1 union select name from users where userid=2;
but mysql return a 1064 error: syntax error near union...
Do u know why?

Help With A Query That Has UNION And SUM
I am trying to join 2 tables (union) and calculate the final quantity like below:

PHP

(SELECT SUM(`sales`.`Quantity`)
FROM  sales
WHERE
`sales`.`SKU` = 'S0089-060927-S0072-bar-exP^223')

UNION ALL

(SELECT SUM(`reversals`.`Quantity`)
FROM  reversals
WHERE
`reversals`.`SKU` = 'S0089-060927-S0072-bar-exP^223')

The result that I am getting when executing this is 2 lines. One is the sales total quantity (let;s say 10) and the other is reversals total quantity (let's say 2). How can I merge so that i have the net quantity (ie 8)?


Union Problem
Can anyone tell me the best way of removing duplicates when using a union on 2 or more Fulltext queries

Conditional Union
My objective is to gather all the type groups for a mailing list. I also would like to add to the list an 'Undefined' item for all the users that are ungrouped:

1. I'm trying to make a conditional union, where a union will occur only if the previous condition is true (if any null typeIDs are found)
2. I would like to make one query only [to use with a php function wich only allows single queries]

So this is a 'sketch' of my query:

SELECT typeID, name FROM pa_users_broadcast_types
UNION
IF((SELECT COUNT(*) FROM pa_users_broadcast WHERE ISNULL(typeID))>0)
SELECT (&#390;') typeID, ('Undefined') name;

Group By In Union
I need some help with this query, i need to be able to group the combined results by "N_U_R_C". The following query does not work because of the line in red.


Quote:

select i.id
, i.id as substitute_for
, i.fd_Date
, i.catid
, i.Make
, i.Model
, i.modelGroup
, i.Description
, i.N_U_R_C as nurc
, i.Price
, i.pic1
from inventory i, inventory_category c
where i.catid=c.id AND c.parent=47 AND i.Model='$model' AND i.Make='$make' AND i.I_IC_C_S!='S' AND i.N_U_R_C!='C')
union all
(select i_sub.id
, i_real.id as substitute_for
, i_sub.fd_Date
, i_sub.catid
, i_af.make
, i_af.model
, i_sub.modelGroup
, i_sub.Description
, i_sub.N_U_R_C as nurc
, i_sub.Price
, i_sub.pic1
from inventory i_real
join inventory_alsofits i_af
on i_af.itemid = i_real.id
join inventory i_sub
on i_af.itemid = i_sub.id
join inventory_category c_real
on i_real.catid = c_real.id
where c_real.parent=47 AND i_af.model='$model' AND i_af.make='$make' AND i_real.I_IC_C_S!='S' AND i_real.N_U_R_C!='C'
ORDER BY i_real.Make='$make')
GROUP BY nurc
ORDER BY $order $sortorder
LIMIT $limitvalue,$limit

Question About UNION
My first post on this site, was recommended to me by a colleague of mine.

Anyway,
What I have is two tables called table1 and table2. I want to search these tables by a users ID. From the result set I wish to grab the ID of all the files associated with this user as fileID. Then I want to search in another table called file for this fileID and from that result set I wish to grab the productID of that file. I then what to search a table called products for the productype. Then what I want to do is from the whole lot, grab a list of producttypes that have been found and a total of how many of those products are associated to the user.

What I have written works, except for one thing. I get the totals and the producttypes for that specific user, but the problem is that because they are coming from a union between table 1 and table 2, I have duplicates in my result set.

(
[0] => Array
(
[producttype] =>
[total] => 0
)

[1] => Array
(
[producttype] => DVD
[total] => 1
)

[2] => Array
(
[producttype] => BOOK
[total] => 1
)

[3] => Array
(
[producttype] => GAME
[total] => 1
)

[4] => Array
(
[producttype] => CD
[total] => 1
)

[5] => Array
(
[producttype] => CD
[total] => 2
)

[6] => Array
(
[producttype] => MAGAZINE
[total] => 2
)

[7] => Array
(
[producttype] => OTHER
[total] => 1
)

)
As you can see I have two lots of CD in my result set, when really I would want them to be grouped together and give me a total of 3, instead of a total of 2 and a seperate total of 1.

How could I possibly do this? Sorry if I have explained things badly, its pretty hard explaining a system to someone who hasn't seen it.

Below is my current SQL statement, which works fine except for grouping totals for identical producttypes

SELECT
p.producttype, COUNT(p.producttype) as total
FROM
table1 as t
LEFT JOIN
file AS f
ON
t.fileID = f.fileID
LEFT JOIN
products AS p
ON
f.ProductID = p.id
WHERE
t.userID = :userID
GROUP BY
p.producttype

)
UNION ALL
(
SELECT
p.producttype, COUNT(p.producttype) as total
FROM
table2 AS t2
LEFT JOIN
file AS f
ON
t2.stickerpictureID = f.stickerpictureID
LEFT JOIN
products AS p
ON
f.ProductID = p.id
WHERE
t2.userID = :userID
GROUP BY
p.producttype
)
ORDER BY
producttype

UNION Question
I am performing a UNION on 3 tables as follows:

SELECT DISTINCT col1_1, col2_2, col3_3
FROM (
SELECT col1, col2, col3 FROM table1
UNION
SELECT col1, col2, col3 FROM table2
UNION
SELECT col1, col2, col3 FROM table3
)
SORTED_TABLE LIMIT 0, 20

All works well but my question is, is it possible to store the name of the table from which each record in the new table has come from. So I'd therefore be able to see that record x has come from table1 originally.

Union Woes.....
I'm having problems with this slightly more complex union query.

1. Users can be members of groups (via usergroupmap mapping table)
2. Groups can have zero users.
3. Users can be members of zero groups.

I'd like a record set that displays the follwing:

|groupname|username|
|ABCGroup|Mark| /*ABCGroup with 3 members*/
|ABCGroup|John|
|ABCGroup|Ted|
|BCDGroup|NULL| /*BCDGroup with 0 members*/
|CDEGroup|John| /*CDEGroup with 2 members*/
|CDEGroup|Ted|
|DEFGroup|Mark| /*DEFGroup with 1 members*/
|NULL|David| /Users who are not in any groups/
|NULL|Frank|
|NULL|Peter|

NOTE:
-Mark and John and Ted are members of more than 1 group!
-If users are not members of any groups, they are listed at the bottom with a NULL groupname column.
-if groups have no members, they have a NULL username column.

I made the following query, but it returns me ALL users, and ALL groups + members.

(SELECT
group.name as c1,
user.name as c2
FROM
group
LEFT JOIN usergroupmap on (group.id = usergroupmap.groupid)
LEFT JOIN user on (user.id = user.groupmap.userid)

WHERE user.id = 1234)

UNION

(SELECT
NULL as c1,
user.name as c2,

FROM
user

WHERE user.id = 1234)

Union Query
is it possible to sum the results of a union all query?

example:

SELECT col1 FROM table WHERE col3 = 'value 1'
UNION ALL
SELECT col2 FROM table WHERE col4 = 'value 1'

can all the results from col1 and col2 be summed together?

Union ALL Tables
I have a content manager that I wrote and I was looking into a simple solution for a feature I am thinking of...

All the tables in the database that my system uses are the same structurally so I want to UNION them all together to do *site searches*.

Is it possible to indicate *via a SQL statement* a UNION of all tables in a database without actually specifying them all individually?

Using Union In A Subquery?
I'm trying to make a query that fetches messages that were created by one of your friends (friendships are stored in a separate table) and was thinking this query would possibly do the trick:

SELECT *
FROM public_messages
WHERE author_id IN
(
(SELECT friend_from FROM friendships WHERE friend_to=1 AND pending=0)
UNION
(SELECT from_to FROM friendships WHERE friend_from=1 AND pending=0)
)

Where the user's id is 1... Running this query gives an error of:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION ( SELECT from_to FROM friendships WHERE friend_from = 1 AND pending = 0 ) ' at line 1

and of course it works fine without the union... Is such a thing possible in one query?

Union Query
I am using Access 2K as a front end to a MYSQL database.

I am trying to run a Union query on the MYSQL database. The query is (much simplified)

SELECT [faxid] as ID from faxdata UNION
SELECT [letid] as ID from letdata UNION
SELECT [memoid] as ID FROM MEMODATA;

I get an ODBC error. The same query runs when the backend files are MDB files and it runs with MYSQL if I only combine 2 tables. Is there some limit with MYSQL on being only able to use a UNION on 2 tables.

Union Query
I am trying to make a union query to join 4 tables. I have reduced the
tables to just 5 fields and made sure that the field types and names are the
same. I keep getting an error message ODBC call failed.

I have tried various combinations of the tables and find that I can use any
2 of them but as soon as a third is included in the statement the query
fails.

Is there a limit on the number of tables in a union query.
The union query looks like this in its simplest form when I have made sure
that the fields names, types and position match but I have also tried by
specifically naming the fields in the same order for each table

select * from T1 union select * from T2 union select * from T3 UNION select
* from T4;

Union Statement
I have three tables all holding seprate data but they have two similar columns: event and date. I want to build a mysql query in php that will list all on the rows in the each of the events' columns with no duplicates. The query below does not do this because duplicate rows are shown for rows that have the same event name but different dates. For example, EVENT1 might be an event in table 1 with date 2006-09-20 and also and event in table 2 with date 2006-09-30 - so EVENT1 would show twice in my list.

$query_race ="SELECT event, date FROM table1 WHERE event LIKE '2007'
UNION
SELECT event, date FROM table2 WHERE event LIKE '2007'
UNION
SELECT event, date FROM table3 WHERE event LIKE '2007'
GROUP BY event";

Is there anyway to pick up the row with just the latest date so that I could have a list with no duplicates and the latest date from all tables?

UNION And Optimization?
My question is about a UNION query to deal with an (annoying) JOIN
over two tables. I am joining over a double column primary key (where the
order of the columns can be changed). This is so slow using a
join, but very fast using a union. How come this is? Code:

Union All With Or Without Sub-select?
i'm using a sqlite database and have to query similar fields spread across 3-5 tables, so in other words, the schema of the tables are the same.

now, what you guys think is faster, more performant in general?

SELECT ... FROM table1 WHERE ...
   UNION ALL
SELECT ... FROM table2 WHERE ...
   ...
ORDER BY ...;

or

SELECT ... FROM
   (SELECT * FROM table1 UNION ALL SELECT * FROM table2 ...)
WHERE ...
ORDER BY ...;

UNION Issue
I'm trying to display info from 2 different tables in a table on my site. I have the structure set to 7 columns and a count of 30 rows. I can get it to work fine if I just use one select statement with desc limit from 1 table.

But what I want is for it to display info from 1 table first that has 20 rows then grab the remaining 10 rows from the other table. I've tried using UNION for this but I keep getting the column error for different column sizes. I'm running mysql 5 with php 5.2.5.

Is there a better way of doing this? From what I understood about mysql 5 you could run 2 select statements. But that doesn't seem to work.

These are the 2 individual queries that work on their own:

$sql = "SELECT * FROM tbl_user tb
INNER JOIN tbl_user_2 tbl
ON tb.user_id=tbl.user_id
WHERE tbl.status > 0 AND
tb.user_check='Y'
ORDER BY
tbl.status DESC";

$sql = "SELECT * FROM tbl_user WHERE user_check='Y' ORDER BY logged_today DESC";

Union 2 Table On 2 Pc
how can join 2 table of 2 db on 2 different pc ?

In sqlServer i just do:
selet * from pc1.dbo..db1.table1
union
selet * from pc2.dbo..db2.table2

in MySql?

UNION With Group By
I am selecting records from two tables:

select a.fileid, a.outby, a.adddate, b.email from table1 a, table2 b where a.outby=b.uid and a.adddate <  date_add(now(), interval -6 day) and a.status in (1,2)  UNION
select a.fileid, a.outby, a.adddate, b.email from table3 a, table2 b where a.outby=b.uid and a.adddate <  date_add(now(), interval -6 day) and a.status in (1,2)

This returns 4 records:
+---------+--------+------------+-------------------+
| fileid  | outby  | adddate    | email             |
+---------+--------+------------+-------------------+
| 0001013 | user01 | 2007-03-31 | User.01@email.com |
| 0001014 | user02 | 2004-02-02 | User.02@email.com |
| 0000096 | user01 | 2006-12-04 | User.01@email.com |
| 0000097 | user01 | 2007-03-30 | User.01@email.com |
+---------+--------+------------+-------------------+

I am trying to group this result set by email. Thus my output should only be:

User.01@email.com
User.02@email.com

Can't seem to hit on the right combination. Can someone assist?

UNION Problem
I had this problem in 4.1.7, upgraded to 4.1.11, but am still having the problem. If I look at WinXP Task Manager, MySQL is taking 99% of CPU cycles and grabbing more memory every few seconds. The first two of these SQL statements work. The 3rd one, which contains a UNION statement, hangs.

1) select distinct(Metadata.metadataID),Formats.format FROM Metadata
JOIN Formats ON Metadata.MetadataID = Formats.MetadataID
WHERE Metadata.Private='0'
AND Metadata.MetadataID IN
(Select Metadata.MetadataID from metadata
where (title like '%pancreas%'));

This returned about 700 valid rows for me.

2) Select keywords.metadataID FROM keywords where keyword like '%pancreas%';

This also returns about 600 valid rows. But when I combine the two in the SQL below, MySQL never returns. It just sits there consuming 99% of the CPU cycles and reducing the system to a grindingly slow pace:

3) select distinct(Metadata.metadataID),Formats.format FROM Metadata
JOIN Formats ON Metadata.MetadataID = Formats.MetadataID
WHERE Metadata.Private='0'
AND Metadata.MetadataID IN
(Select Metadata.MetadataID from metadata
where (title like '%pancreas%')
UNION Select keywords.metadataID FROM keywords where keyword like
'%pancreas%');

Can You Join A Union
I would like to know if and how it is possible to join the *result* of
a union with another table (without first doing individual joins to
each part of the result that then will be combined into a union) ??
For example, I would like to do such a join, if possible, to avoid
doing something like this:

select tableA.col1 as c1 , tableC.col2, tableC.col3, tableC.col4,
tableC.col5, .....
from tableA inner join tableC
on tableA.col1 = tableC.col1
union
select tableB.col1 as c1, tableC.col2, tableC.col3, tableC.col4,
tableC.col5, .....
from tableB inner join tableC
on tableB.col1 = tableC.col1

The problem with the code above is that I will have a lot of wanted
output fields which in the code will be duplicated from tableC in each
part of the union statement, and if I in the future will add a field
it will then have to be added in two places.

Instead of the code above I would like to do extract the output
columns from tableC to only one place, with code something like this:

select c1 , tableC.col2, tableC.col3, tableC.col4, tableC.col5, .....
from tableC inner join
(
select tableA.col1 as c1 from tableA
union
select tableB.col1 as c1 from tableB
) as VirtualUnionTable
on tableC.col1 = VirtualUnionTable.c1

but this does not work (at least not with mysql 4.0.13) and I don't
know how to refer to the result of the union and the join column of
that union (as you can see above I tried to name it with "as
VirtualUnionTable" and then "on... = VirtualUnionTable.c" but it does
not work).

As I mentioned, the purpose was to eleminate the duplication of all
columns from tableC, which I will have to do if I join tableC
individually to the selects which are then combined into a union, as
in the first example above.

Is it even possible to make a join to the result of a union without
doing the joins separately first, and can someone show how that kind
of code would look like ?

ORDER BY With UNION ALL
We have a problem using ORDER BY with UNION ALL.

The problem occurs when using UNION ALL between many complex select's, but I'll try to make things more simple, posting smaller select's.

When I run the select below, which I call select1, query results are ok, and ORDER BY clause is respected, sorting my query. Code:

Union In Mysql 3.23
Does mysql 3.23 supports "union" It doesn't accept the syntax saying i have an error near 'UNION' i took the most simple example and still it doesn't work. Example:

SELECT Custnum
FROM Custnotes
UNION
SELECT Custnum
FROM Note_NoTipul

Whats A Union?
I know how to create a join - correct me if I am wrong, but its
something like the following:

SELECT contacts.firstname,contacts.lastname,address.line_ 1
FROM contacts,address
WHERE contacts.address_hash='$myhashkey'
AND address.hash='$myhashkey';

I have seen mixed references in my books about unions and joins that
make me think they are in some way related. My Core MySQL book, which I
think is great, is unfortunately not clear enough for my head to grasp.

I'd appreciate if someone would could give me a real and an imaginery
world example (thus sample code and perhaps compare apples and oranges
in a shopping list or whatever)...

UNION And MYSQL
I have mysql 4.1.2 and i wrote the followng code:

select tipmodel from Comp;
union
select tipmodel from Comp2;

Because i have two tables:Comp, Comp2, with the same fields: tipmodel. But the union doesn't work. What could be the problem?

Mysql UNION
I have 2 tables with data i need to loop out to a webpage.

Table1
-Field1_ok
-Field2

Table2
-Field1
-Field2-er

I've tried using...

SELECT Field1 AS f1 FROM Table1 UNION SELECT Field1 AS f1

However, not every value in each table is outputted.

Any ideas?

UNION ALL GROUP BY
I have:

SELECT x, count(x)
FROM table1
WHERE ...

UNION ALL

SELECT x, count(x)
FROM table2
WHERE...

UNION ALL

SELECT x, count(x)
FROM table3
WHERE ...

UNION ALL
....
....

and I need to do GROUP BY with all the sentences.

UNION &amp; SQL_CALC_FOUND_ROWS
I have the following query:

SELECT SQL_CALC_FOUND_ROWS * FROM t1 WHERE kind=0 OR kind=1 ORDER BY rank LIMIT 40,10

it would run slowly because 'OR' breaks usage of indexes. So I rewrote it using the UNION:

(SELECT SQL_CALC_FOUND_ROWS * FROM t1 WHERE kind=0 ORDER BY rank LIMIT 50) UNION ALL (SELECT SQL_CALC_FOUND_ROWS * FROM t1 WHERE kind=1 ORDER BY rank LIMIT 50) ORDER BY rank LIMIT 40,10

The problem is that FOUND_ROWS() returns just 100 which is the number of rows in a temporal table created by UNION ALL, but I'd like to get the entire number of rows that have kind of 0 or 1

Union Repeat
which I want to be able to insert into a different database table:

The results are in these three variables which ar being looped:

myString / typenumber / codenumber

How can I insert these loop results into another database table? row by row?

Like this:

auto_id column1 column2 column3
1 value1(myString) value1(typenumber) value1(codenr
2 value2(mystring) value2(typenumber) value2(codenr)

etc....

If I use this: one row is being inserted. Someone said I have to use this but then use the UNION REPEAT.....

<CFQUERY NAME="update" DATASOURCE="">
INSERT INTO dev (dev_volgnr,dev_typenr, dev_nr)
SELECT '#myString#','#typenumber#','#codenumber#'

</CFQUERY>

UNION Problem
I'm having a problem with using UNION to join my query on MYSQL 4.1.22, it work correctly on 5.0.45 but that is not installed on my host so im stuck with 4.1.22.

The problem is that it seems not to be joining the second part of the query. Is there something I can do to make it work on 4.1.22?


Code:


SELECT gameID, round, date, year, hteam, ateam, played, SUM((aFinalGoals *6) + ( aFinalPoints )) AS highest, a.teamName AS team
FROM games g
LEFT JOIN venues v ON ( g.venueID = v.venueID )
LEFT JOIN rounds r ON ( g.roundID = r.roundID )
LEFT JOIN teams a ON ( g.aTeam = a.teamID )
WHERE g.venueID =7
AND played =1
GROUP BY gameID

UNION

SELECT gameID, round, date, year, hteam, ateam, played, SUM((hFinalGoals *6) + ( hFinalPoints ) ) AS highest, h.teamName AS team
FROM games g
LEFT JOIN venues v ON ( g.venueID = v.venueID )
LEFT JOIN rounds r ON ( g.roundID = r.roundID )
LEFT JOIN teams h ON ( g.hTeam = h.teamID )
WHERE g.venueID =7
AND played =1
GROUP BY gameID

ORDER BY highest DESC
LIMIT 5

Mysql Union
I have been developing a mysql application for a month on one machine, time to move to another, much to my surprise it has 3.23.58 and there is no way to change it. Now all of my union queries are broken.
I found one solution:

CREATE TEMPORARY TABLE temp_union TYPE=HEAP select * from asdf;
INSERT INTO temp_union select * from qwer;
SELECT * FROM temp_union;
DROP TABLE temp_union;

Now I ask, how efficient is this? I mostly use the union in two places: a search query where I aggregate a search from three tables, and a favorites list where I aggregrate favorites from three tables. So using the above methods I would need to create 2 temporary tables for each query.

I am using php as a frontend, would it be better to do 3 queries and aggregrate everything in php? the only reason I do it on mysql is because I also need a sorting.

UNION Statement
I have this query and its giving me an error saying "Database error # 1222. The used SELECT statements have a different number of columns". Does anyone know what this means and how can I fix it? The query is:

(SELECT Pay_Rate FROM Employees WHERE Number = '123456' ORDER BY Name ASC) UNION (SELECT * FROM Employee_Schedule WHERE Number = '123456' AND Week_Ending = '2004-04-03' ORDER BY Name ASC)

Maybe I have a wrong statement but heres what I am trying to do... I have two tables Employees and Employee_Schedule. I need the Pay_Rate from the Employees table and everything from the Employee_Schedule (with the condition being met). But I also need to make sure that the Pay_Rate for the employee Name from the Employee table matches the Name from the Employee_Schedule. And, I would like to put all the results into one table.

Union Count
First I'm trying to add together two counts in a union.Code:

select count(id) as count from products where catid=2
union
select count(id) as count from collections where catid=2

How can I get the sum of those two counts?

Union Statements
I am trying to create a union statement to join two queries together.
one of the fields on one of the queries is a constant, ie because it is from the table i want it to output the letter 'B'. When i try to union this with a variable in another query, i get the error: "Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation 'UNION'"

How UNION Is Supposed To Work?
Hello here,
I have a problem with the use of UNION. If I query my database with the following:

Quote:

SELECT column1 FROM mytable WHERE title = "mytitle" UNION SELECT column1 FROM mytable WHERE author = "myauthor"

I get a syntax error! (#1064) Why? I can;t find anything wrong in the query above.


UNION Vs While Loop Question
On Edit: Please disregard this thread; I just stumbled over the problem.

* * * * *

I've been working with the following query (which works):
PHP

$res = mysql_query ("SELECT PxT.URL, PxT.Topic, PxT.Site, PxT.Live, ART.ID, ART.Articles, ART.Site Site2, ART.Live2 FROM px_topics PxT LEFT JOIN px_articles_topics ART ON ART.ID = Pxt.URL WHERE PxT.Site = ART.Site AND PxT.Topic = '$MyURL'") or die (mysql_error());while ($row = mysql_fetch_array ($res)){


As you can see, this query joins tables px_topics (which sets up dynamic pages) and px_articles_topics (which displays articles on the pages created by px_topics). I want to add two more pairs of tables to my query, for a total of six tables:

px_topics
px_articles_topics
px_people
px_articles_people
px_orgs
px_articles_orgs
The tables are virtually identical except that the field named Topics in table px_topics is named Person in px_people and Org in px_orgs.

So I started to work on a UNION query but ran into problems immediately. I had to drop the "or die (mysql_error());" clause to make it work, winding up with the following:


PHP

$res = mysql_query ("SELECT * FROM{ SELECT PxT.URL, PxT.Topic, PxT.Site, PxT.Live, ART.ID, ART.Articles, ART.Site Site2, ART.Live2 FROM px_topics PxT LEFT JOIN px_articles_topics ART ON ART.ID = Pxt.URL WHERE PxT.Site = ART.Site AND PxT.Topic = '$MyURL') }  AS TPO");while ($row = mysql_fetch_array ($res))


But I get an error on the last line. I tried each of the following variations, without luck:


PHP

while ($TPO = mysql_fetch_array ($res))while ($row = mysql_fetch_array ($TPO))


I assume my finished query will look something like this, right?:


PHP

$res = mysql_query ("SELECT * FROM{ SELECT PxT.URL, PxT.Topic, PxT.Site, PxT.Live, ART.ID, ART.Articles, ART.Site Site2, ART.Live2 FROM px_topics PxT LEFT JOIN px_articles_topics ART ON ART.ID = Pxt.URL WHERE PxT.Site = ART.Site AND PxT.Topic = '$MyURL') UNION ALL SELECT ORG.URL, ORG.org, ORG.Site, ORG.Live, ART2.ID, ART2.Articles, ART2.Site Site2, ART2.Live2 FROM px_orgs ORG LEFT JOIN px_articles_orgs ART2 ON ART2.ID = ORG.URL WHERE ORG.Site = ART2.Site AND ORG.Org = '$MyURL') }  AS TPO");while ($row = mysql_fetch_array ($res))

Anyway, I'm not sure if I just need to fix my WHILE LOOP or if there's a problem with my query.



Copyright © 2005-08 www.BigResource.com, All rights reserved