How to use GROUP_CONCAT and UNION in single MySQL Statement - php

I have 2 tables in my database which are identical in structure but contain different records. Each table has the field 'keywords' which contains comma delimited data.
At the moment, I'm running 2 MySQL queries to get 2 different results which I then merge, using the following MySQL Statements:
SELECT GROUP_CONCAT(keywords) keywords FROM table1
and
SELECT GROUP_CONCAT(keywords) keywords FROM table2
I'm sure I should be able to get what I need using a single MySQL statement but all of my attempts to use GROUP_CONCAT and UNION have failed.
Thanks for any pointers/help.

Try this :
SELECT CONCAT(GROUP_CONCAT(t1.keywords),',',GROUP_CONCAT(t2.keywords)) keywords FROM table1 t1, table2 t2
If you don't want duplicate values, then it will be like that :
SELECT GROUP_CONCAT(DISTINCT t.keywords) FROM (
SELECT t1.keywords FROM table1 t1
UNION
SELECT t2.keywords FROM table1 t2
) t

It is as simple as that:
SELECT GROUP_CONCAT(keywords) keywords FROM table1
UNION
SELECT GROUP_CONCAT(keywords) keywords FROM table2
Here is a fiddle.

Related

Display tables data one after one in MySQL?

actually I have two tables ,i.e table 1 and table 2 . I need to display data from both tables . if I use
SELECT * FROM table 1 UNION SELECT * FROM table 2
Now I am getting data randomly from both tables
BUT I need first display table1 data after display table2 data
In practice, this will do what you want (assuming the tables have the same columns):
SELECT * FROM table1
UNION ALL
SELECT * FROM table2;
It is actually safer to use an explicit order by:
SELECT . . .
FROM (SELECT t1.*, 1 as which FROM table1 t1
UNION ALL
SELECT t2.*, 2 as which FROM table2 t2
) t
ORDER BY which;
SQL tables represent unordered sets. There is no ANSI requirement that UNION ALL return values from the first subquery before the second. In practice that works in MySQL.
One way could be adding a column in the both queries which would indicate the source from where it came.
SELECT
*
FROM
(
SELECT *,'T1' AS source FROM table1
UNION
SELECT *,'T2' FROM table2
) AS t
ORDER BY t.source ASC;
See Demo

How to select two additional columns from another table based on id in the main table?

How to select two additional columns from another table based on id in the main table?
SELECT t1.*, t2.*
FROM tbl_setup t1, tbl_specialty t2
WHERE t1.app_id = 12
Use a JOIN:
SELECT * FROM tbl_setup t1
JOIN tbl_speciality t2
ON t1.app_idd = t2.t1_app_id
I am not sure, but I don't think you can use "$" in a MySQL column name without running into problems later.
A nice explanation of MySQL Joins:
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

SELECT Multiple Tables

I'm stuck in a piece of code that does not quite understand.
I have several tables with different names but same fields, but the tables are independent
Something like that:
table1
id
user
title
table2
id
user
title
I need to get in the same query data from two tables but I fail, I try with INNER JOIN, UNION ALL, but not knowing, it misapplied.
Right now I have this:
$mysites = $db->QueryFetchArrayAll("
select *
FROM table1,table2
where table1.user = table2.user AND
table1.user = 1");
foreach($mysites as $mysite){
echo $QUERY['title'];
}
but returned this:
title1.table1
title2.table1
and i like this:
title1.table1
title2.table1
title1.table2
title2.table2
A greeting and thanks
You can use the keyword UNION like this:
SELECT * FROM table1 UNION SELECT * FROM table2
This query will select everything from table1 and merge the results with those from table2. Please note that you have to select the same number of columns from both tables. Moreover, column names and datatypes will be assigned according to first table.
If you want to preserve duplicates add the keyword ALL:
SELECT * FROM table1 UNION ALL SELECT * FROM table2
The question is very unclear.....
Are the ID's the same in each table for each user? If so an INNERJOIN will help
SELECT t1.*, t2.*
FROM table1.t1
INNER JOIN table2.t2
ON t1.id = t2.id
WHERE t1.user = "1"
(Change INNER JOIN to LEFT JOIN if the data could be missing)
If this is not the case, why not put the data from one table into the other, and have just one table with all the data in it?

combine four table into one new table

SELECT a.delivery_date,
a.delivery_hour,
a.price as EX-ANTE,
FROM mms_realtime_dispatch_prices_report a
UNION ALL
SELECT b.delivery_date,
b.delivery_hour,
b.price as EX-POST,
FROM mms_realtime_dispatch_prices_report b
UNION ALL
SELECT c.region,
c.dem_rtdel,
c.date,
FROM pub_demand_lwap c;
UNION ALL
SELECT region,
report,
hour,
SUM(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11)
FROM pub_markets_bids_and_offers
WHERE delivery date=03/16/2011
GROUP BY hour
help! need to combine this four table into one new table no duplicate data
Can you help me in combining this four tables into one table. this is the first time i encounter this. I really need a help :(
In SQL server union works only if there is same number and type of columns return by query.
You need to get your Union query right 1st I can see so many things wrong with Query At the moment,
Your number of columns retunred by each select arent same, Last query is returning 4 columns and other 3,
You are Aliasing Columns in 2nd query, it will not have any effect as Only the Column Names from very first select statement are visible in the result set.
Guessing from the Column names you have Different Data Types that
you are trying to UNION. Datatypes Returned from all selects that you are using in UNION should return the same datatypes e.g
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name1
UNION ALL
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name2
UNION ALL
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name3
and so on....
Once you have met all these condition then you can do something like this to eliminate duplicate rows from you result set
;with CTE
AS
(
SELECT ID_Column, rn = ROW_NUMBER() OVER (PARTITION BY Column1, Column2, Column3... ORDER BY ID ASC)
FROM ( -- All of your UNION ALL Statements Can go here --)q
)
DELETE FROM CTE
WHERE rn = 1

MySQL search multiple tables for information

I'm building a searchfunctionallity where a user can select the different libraries to search in with the provided keywords. Also the AND operator is supported. My problem is that when I try to search for information it gets somehow multiplied or it gets increased exponential??
I'm using a MySQL database and PHP to process the results.
A sample query looks like this, sample tablenames taken for readability:
SELECT table1.id AS table1_id,
table2.id AS table2_id,
table1.*,
table2.*
FROM table1, table2
WHERE (table1.column1 LIKE '%key%' OR table1.column2 LIKE '%key%') OR
(table2.column1 LIKE '%key%' OR table2.column2 LIKE '%key%')
Or when a user provides keywords like 'key AND yek' the queries will look like:
SELECT table1.id AS table1_id,
table2.id AS table2_id,
table1.*,
table2.*
FROM table1, table2
WHERE ( (table1.column1 LIKE '%key%' AND table1.column2 LIKE '%key%') OR
(table1.colum1 LIKE '%yek%' AND table1.colum2 LIKE '%yek%') )
OR
(( table2.column1 LIKE '%key%' AND table2.column2 LIKE '%key%') OR
(table2.colum1 LIKE '%yek%' AND table2.colum2 LIKE '%yek%') )
I've searched arround and came accross UNION, but that won't do the trick. Firstly because of the tables I'm querying are not equal and it's a pretty expensive query. So also because the searchfunctionallity will be used often it's not an option.
In fact I'm querying 5 tables and per table between 2 or 4 columns. I set up a testrow in one of the tables with a unique value so I should get 1 row as result but in fact I'm getting a lot more. When I select all 5 tables I'm getting over 10K resultrows. So my guess is the result gets multiplied some way or another. I've played with the operators AND and OR but so far without any luck.
Is there someone who can help me further in my 'quest' to build a userfriendly searchengine in a webapp?
you should take a look at a real full text search engine, there is many around:
lucene
sphinx
Mysql: MySQL has a full text search engine but it's kind of slow so I don't advise you to use it apart if you want a quick solution
couchDB: that's not really a full text search engine but in your case it might helps but you might be able to create a DB from your current MySQL database and use that only for search purpose.
depending how your table are done, you might want to create a table with all the information you need.
A join will solve the problem of your dataset appearing to 'multiply'.
http://en.wikipedia.org/wiki/Join_%28SQL%29
This requires a field from Table1 to also be present in Table2 and used as a foreign key.
For eg, Table1 and Table2 both have ProductID:
Select * From Table1 Left Outer Join Table2 on Table1.ProductID = Table2.ProductID
Some suggestions:
I would suggest using (INNER?) JOIN instead of SELECT FROM table1, table2. That will narrow the number of tables. This should limit the output considerably.
Look into the DISTINCT keyword (or parallels like GROUP BY), it should further limit the output
DON'T rule out UNION. I don't know about MySQL, but in Oracle's SQL it is often two to three times faster than using an "OR". If you have
-- Admittedly, this query is a bit defective, but I'm trying to demonstrate.
SELECT
table1.data
FROM
table1, table2
WHERE
table1.data = 7
UNION
SELECT
table1.data
FROM
table1, table2
WHERE
table1.data = 8;
that will be far faster than using:
SELECT
table1.data, table2.*
FROM
table1, table2
WHERE
table1.data = 7 OR table1.data = 8;
Overall, I think that you'll see better results using something like this (this is Oracle syntax):
SELECT
ti.id,
t1.data,
t2.*
FROM
table1 t1
JOIN
table2 t2
ON(
t1.id = t2.id
)
WHERE
table1.data LIKE '%foo%'
UNION
SELECT
ti.id,
t1.data,
t2.*
FROM
table1 t1
JOIN
table2 t2
ON(
t1.id = t2.id
)
WHERE
table1.data LIKE '%bar%';
------- EDIT -------
It has been protested that "JOIN will not work as the tables are completely different". So long as there exists some key which exists that can relate one of the tables to another, JOIN will be able to create (effectively) an "uber-table" which has access to all of the data of both tables. If this index does not exist, then you'll probably need some system to concatenate the information outside of the SQL query.
I found the fulltext solutions to 'heavy' for my situation. I've created a query-array where queries per table are stored and later on I've used them for displaying the data I wanted. Everybody thanks for their effort!
I think what you want is to use UNION, which can combine the result of different SELECT queries.
(SELECT id FROM table1 WHERE (table1.column1 LIKE '%key%' OR table1.column2 LIKE '%key%'))
UNION
(SELECT id FROM table2 WHERE (table2.column1 LIKE '%key%' OR table2.column2 LIKE '%key%'))

Categories